<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="generator" content="rustdoc">
    <title>The Rust Language Tutorial</title>

    <link rel="stylesheet" type="text/css" href="The%20Rust%20Language%20Tutorial_files/rust.css">

    <link rel="shortcut icon" href="The%20Rust%20Language%20Tutorial_files/favicon.ico">
<link href="The%20Rust%20Language%20Tutorial_files/css.css" rel="stylesheet" type="text/css">

<link href="The%20Rust%20Language%20Tutorial_files/sbi.css" rel="stylesheet" type="text/css" id="sbi-style"></head>
<body>
    <!--[if lte IE 8]>
    <div class="warning">
        This old browser is unsupported and will most likely display funky
        things.
    </div>
    <![endif]-->

    <div id="versioninfo">
  <img src="The%20Rust%20Language%20Tutorial_files/rust-logo-32x32-blk.png" alt="" height="32" width="32"><br>
  <span class="white-sticker"><a href="http://rust-lang.org/">Rust</a> 0.11.0-pre-nightly</span><br>
</div>
    <h1 class="title">The Rust Language Tutorial(Rust语言教程)</h1>
<nav id="TOC"><ul>
<li><a href="#introduction">1 Introduction(介绍)</a></ul>
	<ul>
<li><a href="#scope">1.1 Scope(范围)</a></li>
<li><a href="#conventions">1.2 Conventions(约定)</a></li>
    </ul>
</li>
<li><a href="#getting-started">2 Getting started(开始)</a><ul>
<li><a href="#compiling-your-first-program">2.1 Compiling your first program(编译你第一个程序)</a><ul></ul></li>
<li><a href="#editing-rust-code">2.2 Editing Rust code(编辑Rust代码)</a><ul></ul></li></ul></li>
<li><a href="#syntax-basics">3 Syntax basics(基本语法)</a><ul>
<li><a href="#expressions-and-semicolons">3.1 Expressions and semicolons(表达式和语义)</a><ul></ul></li>
<li><a href="#primitive-types-and-literals">3.2 Primitive types and literals(基本类型和文字)</a><ul></ul></li>
<li><a href="#operators">3.3 Operators(运算符)</a><ul></ul></li>
<li><a href="#syntax-extensions">3.4 Syntax extensions(扩展语法)</a><ul></ul></li></ul></li>
<li><a href="#control-structures">4 Control structures(控制结构)</a><ul>
<li><a href="#conditionals">4.1 Conditionals(条件)</a><ul></ul></li>
<li><a href="#pattern-matching">4.2 Pattern matching(模式匹配)</a><ul></ul></li>
<li><a href="#loops">4.3 Loops(循环)</a><ul></ul></li></ul></li>
<li><a href="#data-structures">5 Data structures(数据结构)</a><ul>
<li><a href="#structs">5.1 Structs(结构)</a><ul></ul></li>
<li><a href="#enums">5.2 Enums(枚举)</a><ul></ul></li>
<li><a href="#tuples">5.3 Tuples(元组)</a><ul></ul></li>
<li><a href="#tuple-structs">5.4 Tuple structs(元组结构)</a><ul></ul></li></ul></li>
<li><a href="#functions">6 Functions(函数)</a><ul></ul></li>
<li><a href="#destructors">7 Destructors(解构器)</a><ul></ul></li>
<li><a href="#ownership">8 Ownership(所有权)</a><ul></ul></li>
<li><a href="#implementing-a-linked-list">9 Implementing a linked list(实现链接表)</a><ul>
<li><a href="#boxes">9.1 Boxes(封装)</a><ul></ul></li>
<li><a href="#move-semantics">9.2 Move semantics(Move语义)</a><ul></ul></li>
<li><a href="#references">9.3 References(参考)</a><ul></ul></li>
<li><a href="#lists-of-other-types">9.4 Lists of other types(其他类型列表)</a><ul></ul></li>
<li><a href="#defining-list-equality-with-generics">9.5 Defining list equality with generics(用泛型定义列表)</a><ul></ul></li></ul></li>
<li><a href="#more-on-boxes">10 More on boxes(更多有关封装)</a><ul></ul></li>
<li><a href="#references-1">11 References(引用)</a><ul>
<li><a href="#freezing">11.1 Freezing(冻结)</a><ul></ul></li></ul></li>
<li><a href="#dereferencing-pointers">12 Dereferencing pointers(解引用指针)</a><ul></ul></li>
<li><a href="#vectors-and-strings">13 Vectors and strings(矢量和字符串)</a><ul></ul></li>
<li><a href="#ownership-escape-hatches">14 Ownership escape hatches(所有权脱离通道)</a><ul></ul></li>
<li><a href="#closures">15 Closures(闭包)</a><ul>
<li><a href="#owned-closures">15.1 Owned closures(自有闭包)</a><ul></ul></li>
<li><a href="#closure-compatibility">15.2 Closure compatibility(闭包兼容性)</a><ul></ul></li></ul></li>
<li><a href="#methods">16 Methods(方法)</a><ul></ul></li>
<li><a href="#generics">17 Generics(泛型)</a><ul>
<li><a href="#traits">17.1 Traits(特性)</a><ul></ul></li>
<li><a href="#declaring-and-implementing-traits">17.2 Declaring and implementing traits(声明和实现特性)</a><ul></ul></li>
<li><a href="#default-method-implementations-in-trait-definitions">17.3 Default method implementations in trait definitions(特性定义中默认方法实现)</a><ul></ul></li>
<li><a href="#type-parameterized-traits">17.4 Type-parameterized traits(类型参数化的特性)</a><ul></ul></li>
<li><a href="#bounded-type-parameters-and-static-method-dispatch">17.5 Bounded type parameters and static method dispatch(绑定类型参数和静态方法调度)</a><ul></ul></li>
<li><a href="#trait-objects-and-dynamic-method-dispatch">17.6 Trait objects and dynamic method dispatch(特性对象和动态方法调度)</a><ul></ul></li>
<li><a href="#trait-inheritance">17.7 Trait inheritance(特性继承)</a><ul></ul></li>
<li><a href="#deriving-implementations-for-traits">17.8 Deriving implementations for traits(特性派生实现)</a><ul></ul></li></ul></li>
<li><a href="#crates-and-the-module-system">18 Crates and the module system(Crate和模块系统)</a><ul>
<li><a href="#crates">18.1 Crates</a><ul></ul></li>
<li><a href="#the-module-hierarchy">18.2 The module hierarchy(模块系统)</a><ul></ul></li>
<li><a href="#paths-and-visibility">18.3 Paths and visibility(路径和可见性)</a><ul></ul></li>
<li><a href="#files-and-modules">18.4 Files and modules(文件和模块)</a><ul></ul></li>
<li><a href="#importing-names-into-the-local-scope">18.5 Importing names into the local scope(在局部范围引进名字)</a><ul></ul></li>
<li><a href="#reexporting-names">18.6 Reexporting names(重新输出名字)</a><ul></ul></li>
<li><a href="#using-libraries">18.7 Using libraries(使用库)</a><ul></ul></li>
<li><a href="#crate-metadata-and-settings">18.8 Crate metadata and settings(crate元数据和设置)</a><ul></ul></li>
<li><a href="#a-minimal-example">18.9 A minimal example(小例子)</a><ul></ul></li>
<li><a href="#the-standard-library-and-the-prelude">18.10 The standard library and the prelude(标准库和预装模块)</a><ul></ul></li></ul></li>
<li><a href="#what-next?">19 What next?(下一步)</a><ul></ul></li></ul></nav>
<h1 id="introduction" class="section-header"><a href="#introduction">1 Introduction(介绍)</a></h1>
<p>Rust is a programming language with a focus on type safety, memory
safety, concurrency and performance. It is intended for writing
large-scale, high-performance software that is free from several
classes of common errors. Rust has a sophisticated memory model that
encourages efficient data structures and safe concurrency patterns,
forbidding invalid memory accesses that would otherwise cause
segmentation faults. It is statically typed and compiled ahead of
time.</p>

<p>As a multi-paradigm language, Rust supports writing code in
procedural, functional and object-oriented styles. Some of its
pleasant high-level features include:</p>
作为一个多范式语言，Rust支持编写代码用过程式(和命令式同义),
函数式以及面向对象风格,它的一些高阶特性包括:
<ul>
<li><strong>Type inference(类型推断).</strong> Type annotations on local variable declarations
are optional.</li>
<li><strong>Safe task-based concurrency(安全任务并发).</strong> Rust's lightweight tasks do not share
memory, instead communicating through messages.</li>
<li><strong>Higher-order functions(高阶函数).</strong> Efficient and flexible closures provide
iteration and other control structures</li>
<li><strong>Pattern matching and algebraic data types(模式匹配和代数数据类型).</strong> Pattern matching on
Rust's enumeration types (a more powerful version of C's enums,
similar to algebraic data types in functional languages) is a
compact and expressive way to encode program logic.</li>
<li><strong>Polymorphism(多态性).</strong> Rust has type-parametric functions and
types, type classes and OO-style interfaces.Rust有类型参数化的函数,类型,类型类以及面向对象风格的结构</li>
</ul>

<h2 id="scope" class="section-header"><a href="#scope">1.1 Scope(范围)</a></h2>
<p>This is an introductory tutorial for the Rust programming language. It
covers the fundamentals of the language, including the syntax, the
type system and memory model, generics, and modules. <a href="#what-next?">Additional
tutorials</a> cover specific language features in greater
depth.</p>

<p>This tutorial assumes that the reader is already familiar with one or
more languages in the C family. Understanding of pointers and general
memory management techniques will help.</p>

<h2 id="conventions" class="section-header"><a href="#conventions">1.2 Conventions(约定)</a></h2>
<p>Throughout the tutorial, language keywords and identifiers defined in
example code are displayed in <code>code font</code>.</p>

<p>Code snippets are indented, and also shown in a monospaced font. Not
all snippets constitute whole programs. For brevity, we'll often show
fragments of programs that don't compile on their own. To try them
out, you might have to wrap them in <code>fn main() { ... }</code>, and make sure
they don't contain references to names that aren't actually defined.</p>

<blockquote>
<p><em>Warning:</em> Rust is a language under ongoing development. Notes
about potential changes to the language, implementation
deficiencies, and other caveats appear offset in blockquotes.</p>
</blockquote>

<h1 id="getting-started" class="section-header"><a href="#getting-started">2 Getting started(开始)</a></h1>
<blockquote>
<p><em>Warning:</em> The tarball and installer links are for the most recent
release, not master. To use master, you <strong>must</strong> build from <a href="https://github.com/mozilla/rust.git">git</a>.</p>
</blockquote>

<p>The Rust compiler currently must be built from a <a href="http://static.rust-lang.org/dist/rust-nightly.tar.gz">tarball</a> or <a href="https://github.com/mozilla/rust.git">git</a>, unless
you are on Windows, in which case using the <a href="http://static.rust-lang.org/dist/rust-nightly-install.exe">installer</a> is
recommended. There is a list of community-maintained nightly builds and
packages <a href="https://github.com/mozilla/rust/wiki/Doc-packages,-editors,-and-other-tools">on the wiki</a>.</p>

<p>Since the Rust compiler is written in Rust, it must be built by
a precompiled "snapshot" version of itself (made in an earlier state
of development). The source build automatically fetches these snapshots
from the Internet on our supported platforms.</p>

<p>Snapshot binaries are currently built and tested on several platforms:</p>

<ul>
<li>Windows (7, 8, Server 2008 R2), x86 only</li>
<li>Linux (2.6.18 or later, various distributions), x86 and x86-64</li>
<li>OSX 10.7 (Lion) or greater, x86 and x86-64</li>
</ul>

<p>You may find that other platforms work, but these are our "tier 1"
supported build environments that are most likely to work.</p>

<blockquote>
<p><em>Note:</em> Windows users should read the detailed
<a href="https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust">Getting started</a> notes on the wiki. Even when using
the binary installer, the Windows build requires a MinGW installation,
the precise details of which are not discussed here.</p>
</blockquote>

<p>To build from source you will also need the following prerequisite
packages:</p>

<ul>
<li>g++ 4.7 or clang++ 3.x</li>
<li>python 2.6 or later (but not 3.x)</li>
<li>perl 5.0 or later</li>
<li>gnu make 3.81 or later</li>
<li>curl</li>
</ul>

<p>If you've fulfilled those prerequisites, something along these lines
should work.</p>

<pre><code class="language-{.notrust}">$ curl -O http://static.rust-lang.org/dist/rust-nightly.tar.gz
$ tar -xzf rust-nightly.tar.gz
$ cd rust-nightly
$ ./configure
$ make &amp;&amp; make install</code></pre>

<p>You may need to use <code>sudo make install</code> if you do not normally have
permission to modify the destination directory. The install locations
can be adjusted by passing a <code>--prefix</code> argument to
<code>configure</code>. Various other options are also supported: pass <code>--help</code>
for more information on them.</p>

<p>When complete, <code>make install</code> will place several programs into
<code>/usr/local/bin</code>: <code>rustc</code>, the Rust compiler, and <code>rustdoc</code>, the
API-documentation tool.</p>

<h2 id="compiling-your-first-program" class="section-header"><a href="#compiling-your-first-program">2.1 Compiling your first program(编译你第一个程序)</a></h2>
<p>Rust program files are, by convention, given the extension <code>.rs</code>. Say
we have a file <code>hello.rs</code> containing this program:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"hello?"</span>);
}
</pre>

<blockquote>
<p><em>Note:</em> An identifier followed by an exclamation point, like
<code>println!</code>, is a macro invocation.  Macros are explained
<a href="#syntax-extensions">later</a>; for now just remember to include the
exclamation point.</p>
</blockquote>

<p>If the Rust compiler was installed successfully, running <code>rustc
hello.rs</code> will produce an executable called <code>hello</code> (or <code>hello.exe</code> on
Windows) which, upon running, will likely do exactly what you expect.</p>

<p>The Rust compiler tries to provide useful information when it encounters an
error. If you introduce an error into the program (for example, by changing
<code>println!</code> to some nonexistent macro), and then compile it, you'll see
an error message like this:</p>

<pre><code class="language-{.notrust}">hello.rs:2:5: 2:24 error: macro undefined: 'print_with_unicorns'
hello.rs:2     print_with_unicorns!("hello?");
               ^~~~~~~~~~~~~~~~~~~</code></pre>

<p>In its simplest form, a Rust program is a <code>.rs</code> file with some types
and functions defined in it. If it has a <code>main</code> function, it can be
compiled to an executable. Rust does not allow code that's not a
declaration to appear at the top level of the file: all statements must
live inside a function.  Rust programs can also be compiled as
libraries, and included in other programs, even ones not written in Rust.</p>

<h2 id="editing-rust-code" class="section-header"><a href="#editing-rust-code">2.2 Editing Rust code(编辑Rust代码)</a></h2>
<p>There are vim highlighting and indentation scripts in the Rust source
distribution under <code>src/etc/vim/</code>. There is an emacs mode under
<code>src/etc/emacs/</code> called <code>rust-mode</code>, but do read the instructions
included in that directory. In particular, if you are running emacs
24, then using emacs's internal package manager to install <code>rust-mode</code>
is the easiest way to keep it up to date. There is also a package for
Sublime Text 2, available both <a href="http://github.com/dbp/sublime-rust">standalone</a> and through
<a href="http://wbond.net/sublime_packages/package_control">Sublime Package Control</a>, and support for Kate
under <code>src/etc/kate</code>.</p>

<p>A community-maintained list of available Rust tooling is <a href="https://github.com/mozilla/rust/wiki/Doc-packages,-editors,-and-other-tools">on the
wiki</a>.</p>

<p>There is ctags support via <code>src/etc/ctags.rust</code>, but many other
tools and editors are not yet supported. If you end up writing a Rust
mode for your favorite editor, let us know so that we can link to it.</p>

<h1 id="syntax-basics" class="section-header"><a href="#syntax-basics">3 Syntax basics(基本语法)</a></h1>
<p>Assuming you've programmed in any C-family language (C++, Java,
JavaScript, C#, or PHP), Rust will feel familiar. Code is arranged
in blocks delineated by curly braces; there are control structures
for branching and looping, like the familiar <code>if</code> and <code>while</code>; function
calls are written <code>myfunc(arg1, arg2)</code>; operators are written the same
and mostly have the same precedence as in C; comments are again like C;
module names are separated with double-colon (<code>::</code>) as with C++.</p>

<p>The main surface difference to be aware of is that the condition at
the head of control structures like <code>if</code> and <code>while</code> does not require
parentheses, while their bodies <em>must</em> be wrapped in
braces. Single-statement, unbraced bodies are not allowed.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">main</span>() {<span class="comment">
    /* A simple loop */
    </span><span class="kw">loop</span> {<span class="comment">
        // A tricky calculation
        </span><span class="kw">if</span> <span class="ident">universe</span>::<span class="ident">recalibrate</span>() {
            <span class="kw">return</span>;
        }
    }
}
</pre>

<p>The <code>let</code> keyword introduces a local variable. Variables are immutable by
default. To introduce a local variable that you can re-assign later, use <code>let
mut</code> instead.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">hi</span> <span class="op">=</span> <span class="string">"hi"</span>;
<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">count</span> <span class="op">=</span> <span class="number">0</span>;

<span class="kw">while</span> <span class="ident">count</span> <span class="op">&lt;</span> <span class="number">10</span> {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"count is {}"</span>, <span class="ident">count</span>);
    <span class="ident">count</span> <span class="op">+=</span> <span class="number">1</span>;
}
</pre>

<p>Although Rust can almost always infer the types of local variables, you can
specify a variable's type by following it in the <code>let</code> with a colon, then the
type name. Static items, on the other hand, always require a type annotation.</p>
<pre class="rust "><span class="kw">static</span> <span class="ident">MONSTER_FACTOR</span>: <span class="ident">f64</span> <span class="op">=</span> <span class="number">57.8</span>;
<span class="kw">let</span> <span class="ident">monster_size</span> <span class="op">=</span> <span class="ident">MONSTER_FACTOR</span> <span class="op">*</span> <span class="number">10.0</span>;
<span class="kw">let</span> <span class="ident">monster_size</span>: <span class="ident">int</span> <span class="op">=</span> <span class="number">50</span>;
</pre>

<p>Local variables may shadow earlier declarations, as in the previous example:
<code>monster_size</code> was first declared as a <code>f64</code>, and then a second
<code>monster_size</code> was declared as an <code>int</code>. If you were to actually compile this
example, though, the compiler would determine that the first <code>monster_size</code> is
unused and issue a warning (because this situation is likely to indicate a
programmer error). For occasions where unused variables are intentional, their
names may be prefixed with an underscore to silence the warning, like <code>let
_monster_size = 50;</code>.</p>

<p>Rust identifiers start with an alphabetic
character or an underscore, and after that may contain any sequence of
alphabetic characters, numbers, or underscores. The preferred style is to
write function, variable, and module names with lowercase letters, using
underscores where they help readability, while writing types in camel case.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">my_variable</span> <span class="op">=</span> <span class="number">100</span>;
<span class="kw">type</span> <span class="ident">MyType</span> <span class="op">=</span> <span class="ident">int</span>;<span class="comment">     // primitive types are _not_ camel case
</span></pre>

<h2 id="expressions-and-semicolons" class="section-header"><a href="#expressions-and-semicolons">3.1 Expressions and semicolons(表达式和语义)</a></h2>
<p>Though it isn't apparent in all code, there is a fundamental
difference between Rust's syntax and predecessors like C.
Many constructs that are statements in C are expressions
in Rust, allowing code to be more concise. For example, you might
write a piece of code like this:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">price</span>;
<span class="kw">if</span> <span class="ident">item</span> <span class="op">==</span> <span class="string">"salad"</span> {
    <span class="ident">price</span> <span class="op">=</span> <span class="number">3.50</span>;
} <span class="kw">else</span> <span class="kw">if</span> <span class="ident">item</span> <span class="op">==</span> <span class="string">"muffin"</span> {
    <span class="ident">price</span> <span class="op">=</span> <span class="number">2.25</span>;
} <span class="kw">else</span> {
    <span class="ident">price</span> <span class="op">=</span> <span class="number">2.00</span>;
}
</pre>

<p>But, in Rust, you don't have to repeat the name <code>price</code>:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">price</span> <span class="op">=</span>
    <span class="kw">if</span> <span class="ident">item</span> <span class="op">==</span> <span class="string">"salad"</span> {
        <span class="number">3.50</span>
    } <span class="kw">else</span> <span class="kw">if</span> <span class="ident">item</span> <span class="op">==</span> <span class="string">"muffin"</span> {
        <span class="number">2.25</span>
    } <span class="kw">else</span> {
        <span class="number">2.00</span>
    };
</pre>

<p>Both pieces of code are exactly equivalent: they assign a value to
<code>price</code> depending on the condition that holds. Note that there
are no semicolons in the blocks of the second snippet. This is
important: the lack of a semicolon after the last statement in a
braced block gives the whole block the value of that last expression.</p>

<p>Put another way, the semicolon in Rust <em>ignores the value of an expression</em>.
Thus, if the branches of the <code>if</code> had looked like <code>{ 4; }</code>, the above example
would simply assign <code>()</code> (unit or void) to <code>price</code>. But without the semicolon, each
branch has a different value, and <code>price</code> gets the value of the branch that
was taken.</p>

<p>In short, everything that's not a declaration (declarations are <code>let</code> for
variables; <code>fn</code> for functions; and any top-level named items such as
<a href="#traits">traits</a>, <a href="#enums">enum types</a>, and static items) is an
expression, including function bodies.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">is_four</span>(<span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment">
   // No need for a return statement. The result of the expression
   // is used as the return value.
   </span><span class="ident">x</span> <span class="op">==</span> <span class="number">4</span>
}
</pre>

<h2 id="primitive-types-and-literals" class="section-header"><a href="#primitive-types-and-literals">3.2 Primitive types and literals(基本类型和文字)</a></h2>
<p>There are general signed and unsigned integer types, <code>int</code> and <code>uint</code>,
as well as 8-, 16-, 32-, and 64-bit variants, <code>i8</code>, <code>u16</code>, etc.
Integers can be written in decimal (<code>144</code>), hexadecimal (<code>0x90</code>), octal (<code>0o70</code>), or
binary (<code>0b10010000</code>) base. Each integral type has a corresponding literal
suffix that can be used to indicate the type of a literal: <code>i</code> for <code>int</code>,
<code>u</code> for <code>uint</code>, <code>i8</code> for the <code>i8</code> type.</p>

<p>In the absence of an integer literal suffix, Rust will infer the
integer type based on type annotations and function signatures in the
surrounding program. In the absence of any type information at all,
Rust will assume that an unsuffixed integer literal has type
<code>int</code>.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">a</span> <span class="op">=</span> <span class="number">1</span>;<span class="comment">       // `a` is an `int`
</span><span class="kw">let</span> <span class="ident">b</span> <span class="op">=</span> <span class="number">10i</span>;<span class="comment">     // `b` is an `int`, due to the `i` suffix
</span><span class="kw">let</span> <span class="ident">c</span> <span class="op">=</span> <span class="number">100u</span>;<span class="comment">    // `c` is a `uint`
</span><span class="kw">let</span> <span class="ident">d</span> <span class="op">=</span> <span class="number">1000i32</span>;<span class="comment"> // `d` is an `i32`
</span></pre>

<p>There are two floating-point types: <code>f32</code>, and <code>f64</code>.
Floating-point numbers are written <code>0.0</code>, <code>1e6</code>, or <code>2.1e-4</code>.
Like integers, floating-point literals are inferred to the correct type.
Suffixes <code>f32</code>, and <code>f64</code> can be used to create literals of a specific type.</p>

<p>The keywords <code>true</code> and <code>false</code> produce literals of type <code>bool</code>.</p>

<p>Characters, the <code>char</code> type, are four-byte Unicode codepoints,
whose literals are written between single quotes, as in <code>'x'</code>.
Just like C, Rust understands a number of character escapes, using the backslash
character, such as <code>\n</code>, <code>\r</code>, and <code>\t</code>. String literals,
written between double quotes, allow the same escape sequences, and do no
other processing, unlike languages such as PHP or shell.</p>

<p>On the other hand, raw string literals do not process any escape sequences.
They are written as <code>r##"blah"##</code>, with a matching number of zero or more <code>#</code>
before the opening and after the closing quote, and can contain any sequence of
characters except their closing delimiter.  More on strings
<a href="#vectors-and-strings">later</a>.</p>

<p>The unit type, written <code>()</code>, has a single value, also written <code>()</code>.</p>

<h2 id="operators" class="section-header"><a href="#operators">3.3 Operators(运算符)</a></h2>
<p>Rust's set of operators contains very few surprises. Arithmetic is done with
<code>*</code>, <code>/</code>, <code>%</code>, <code>+</code>, and <code>-</code> (multiply, quotient, remainder, add, and subtract). <code>-</code> is
also a unary prefix operator that negates numbers. As in C, the bitwise operators
<code>&gt;&gt;</code>, <code>&lt;&lt;</code>, <code>&amp;</code>, <code>|</code>, and <code>^</code> are also supported.</p>

<p>Note that, if applied to an integer value, <code>!</code> flips all the bits (bitwise
NOT, like <code>~</code> in C).</p>

<p>The comparison operators are the traditional <code>==</code>, <code>!=</code>, <code>&lt;</code>, <code>&gt;</code>,
<code>&lt;=</code>, and <code>&gt;=</code>. Short-circuiting (lazy) boolean operators are written
<code>&amp;&amp;</code> (and) and <code>||</code> (or).</p>

<p>For compile-time type casting, Rust uses the binary <code>as</code> operator.  It takes
an expression on the left side and a type on the right side and will, if a
meaningful conversion exists, convert the result of the expression to the
given type. Generally, <code>as</code> is only used with the primitive numeric types or
pointers, and is not overloadable.  <a href="http://static.rust-lang.org/doc/master/std/cast/fn.transmute.html"><code>transmute</code></a> can be used for
unsafe C-like casting of same-sized types.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span>: <span class="ident">f64</span> <span class="op">=</span> <span class="number">4.0</span>;
<span class="kw">let</span> <span class="ident">y</span>: <span class="ident">uint</span> <span class="op">=</span> <span class="ident">x</span> <span class="kw">as</span> <span class="ident">uint</span>;
<span class="macro">assert</span><span class="macro">!</span>(<span class="ident">y</span> <span class="op">==</span> <span class="number">4u</span>);
</pre>

<h2 id="syntax-extensions" class="section-header"><a href="#syntax-extensions">3.4 Syntax extensions(扩展语法)</a></h2>
<p><em>Syntax extensions</em> are special forms that are not built into the language,
but are instead provided by the libraries. To make it clear to the reader when
a name refers to a syntax extension, the names of all syntax extensions end
with <code>!</code>. The standard library defines a few syntax extensions, the most
useful of which is <a href="http://static.rust-lang.org/doc/master/std/fmt/index.html"><code>format!</code></a>, a <code>sprintf</code>-like text formatter that you
will often see in examples, and its related family of macros: <code>print!</code>,
<code>println!</code>, and <code>write!</code>.</p>

<p><code>format!</code> draws syntax from Python, but contains many of the same principles
that <a href="http://en.cppreference.com/w/cpp/io/c/fprintf">printf</a> has. Unlike printf, <code>format!</code> will give you a compile-time
error when the types of the directives don't match the types of the arguments.</p>
<pre class="rust "><span class="comment">
// `{}` will print the "default format" of a type
</span><span class="macro">println</span><span class="macro">!</span>(<span class="string">"{} is {}"</span>, <span class="string">"the answer"</span>, <span class="number">43</span>);<span class="comment">

// `{:?}` will conveniently print any type
</span><span class="macro">println</span><span class="macro">!</span>(<span class="string">"what is this thing: {:?}"</span>, <span class="ident">mystery_object</span>);
</pre>

<p>You can define your own syntax extensions with the macro system. For details,
see the <a href="http://static.rust-lang.org/doc/master/guide-macros.html">macro tutorial</a>. Note that macro definition is currently
considered an unstable feature.</p>

<h1 id="control-structures" class="section-header"><a href="#control-structures">4 Control structures(控制结构)</a></h1>
<h2 id="conditionals" class="section-header"><a href="#conditionals">4.1 Conditionals(条件)</a></h2>
<p>We've seen <code>if</code> expressions a few times already. To recap, braces are
compulsory, an <code>if</code> can have an optional <code>else</code> clause, and multiple
<code>if</code>/<code>else</code> constructs can be chained together:</p>
<pre class="rust "><span class="kw">if</span> <span class="boolval">false</span> {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"that's odd"</span>);
} <span class="kw">else</span> <span class="kw">if</span> <span class="boolval">true</span> {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"right"</span>);
} <span class="kw">else</span> {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"neither true nor false"</span>);
}
</pre>

<p>The condition given to an <code>if</code> construct <em>must</em> be of type <code>bool</code> (no
implicit conversion happens). If the arms are blocks that have a
value, this value must be of the same type for every arm in which
control reaches the end of the block:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">signum</span>(<span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
    <span class="kw">if</span> <span class="ident">x</span> <span class="op">&lt;</span> <span class="number">0</span> { <span class="op">-</span><span class="number">1</span> }
    <span class="kw">else</span> <span class="kw">if</span> <span class="ident">x</span> <span class="op">&gt;</span> <span class="number">0</span> { <span class="number">1</span> }
    <span class="kw">else</span> { <span class="number">0</span> }
}
</pre>

<h2 id="pattern-matching" class="section-header"><a href="#pattern-matching">4.2 Pattern matching(模式匹配)</a></h2>
<p>Rust's <code>match</code> construct is a generalized, cleaned-up version of C's
<code>switch</code> construct. You provide it with a value and a number of
<em>arms</em>, each labelled with a pattern, and the code compares the value
against each pattern in order until one matches. The matching pattern
executes its corresponding arm.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">my_number</span> <span class="op">=</span> <span class="number">1</span>;
<span class="kw">match</span> <span class="ident">my_number</span> {
  <span class="number">0</span>     <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"zero"</span>),
  <span class="number">1</span> <span class="op">|</span> <span class="number">2</span> <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"one or two"</span>),
  <span class="number">3</span>..<span class="number">10</span> <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"three to ten"</span>),
  _     <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"something else"</span>)
}
</pre>

<p>Unlike in C, there is no "falling through" between arms: only one arm
executes, and it doesn't have to explicitly <code>break</code> out of the
construct when it is finished.</p>

<p>A <code>match</code> arm consists of a <em>pattern</em>, then a fat arrow <code>=&gt;</code>, followed
by an <em>action</em> (expression). Each case is separated by commas. It is
often convenient to use a block expression for each case, in which case
the commas are optional as shown below. Literals are valid patterns and
match only their own value. A single arm may match multiple different
patterns by combining them with the pipe operator (<code>|</code>), so long as every
pattern binds the same set of variables. Ranges of numeric literal
patterns can be expressed with two dots, as in <code>M..N</code>. The underscore
(<code>_</code>) is a wildcard pattern that matches any single value. (<code>..</code>) is a
different wildcard that can match one or more fields in an <code>enum</code> variant.</p>
<pre class="rust "><span class="kw">match</span> <span class="ident">my_number</span> {
  <span class="number">0</span> <span class="op">=&gt;</span> { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"zero"</span>) }
  _ <span class="op">=&gt;</span> { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"something else"</span>) }
}
</pre>

<p><code>match</code> constructs must be <em>exhaustive</em>: they must have an arm
covering every possible case. For example, the typechecker would
reject the previous example if the arm with the wildcard pattern was
omitted.</p>

<p>A powerful application of pattern matching is <em>destructuring</em>:
matching in order to bind names to the contents of data types.</p>

<blockquote>
<p><em>Note:</em> The following code makes use of tuples (<code>(f64, f64)</code>) which
are explained in section 5.3. For now you can think of tuples as a list of
items.</p>
</blockquote>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>;
<span class="kw">fn</span> <span class="ident">angle</span>(<span class="ident">vector</span>: (<span class="ident">f64</span>, <span class="ident">f64</span>)) <span class="op">-&gt;</span> <span class="ident">f64</span> {
    <span class="kw">let</span> <span class="ident">pi</span> <span class="op">=</span> <span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span>;
    <span class="kw">match</span> <span class="ident">vector</span> {
      (<span class="number">0.0</span>, <span class="ident">y</span>) <span class="kw">if</span> <span class="ident">y</span> <span class="op">&lt;</span> <span class="number">0.0</span> <span class="op">=&gt;</span> <span class="number">1.5</span> <span class="op">*</span> <span class="ident">pi</span>,
      (<span class="number">0.0</span>, _) <span class="op">=&gt;</span> <span class="number">0.5</span> <span class="op">*</span> <span class="ident">pi</span>,
      (<span class="ident">x</span>, <span class="ident">y</span>) <span class="op">=&gt;</span> (<span class="ident">y</span> <span class="op">/</span> <span class="ident">x</span>).<span class="ident">atan</span>()
    }
}
</pre>

<p>A variable name in a pattern matches any value, <em>and</em> binds that name
to the value of the matched value inside of the arm's action. Thus, <code>(0.0,
y)</code> matches any tuple whose first element is zero, and binds <code>y</code> to
the second element. <code>(x, y)</code> matches any two-element tuple, and binds both
elements to variables. <code>(0.0,_)</code> matches any tuple whose first element is zero
and does not bind anything to the second element.</p>

<p>A subpattern can also be bound to a variable, using <code>variable @ pattern</code>. For
example:</p>
<pre class="rust "><span class="kw">match</span> <span class="ident">age</span> {
    <span class="ident">a</span> <span class="kw-2">@</span> <span class="number">0</span>..<span class="number">20</span> <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{} years old"</span>, <span class="ident">a</span>),
    _ <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"older than 21"</span>)
}
</pre>

<p>Any <code>match</code> arm can have a guard clause (written <code>if EXPR</code>), called a
<em>pattern guard</em>, which is an expression of type <code>bool</code> that
determines, after the pattern is found to match, whether the arm is
taken or not. The variables bound by the pattern are in scope in this
guard expression. The first arm in the <code>angle</code> example shows an
example of a pattern guard.</p>

<p>You've already seen simple <code>let</code> bindings, but <code>let</code> is a little
fancier than you've been led to believe. It, too, supports destructuring
patterns. For example, you can write this to extract the fields from a
tuple, introducing two variables at once: <code>a</code> and <code>b</code>.</p>
<pre class="rust "><span class="kw">let</span> (<span class="ident">a</span>, <span class="ident">b</span>) <span class="op">=</span> <span class="ident">get_tuple_of_two_ints</span>();
</pre>

<p>Let bindings only work with <em>irrefutable</em> patterns: that is, patterns
that can never fail to match. This excludes <code>let</code> from matching
literals and most <code>enum</code> variants.</p>

<h2 id="loops" class="section-header"><a href="#loops">4.3 Loops(循环)</a></h2>
<p><code>while</code> denotes a loop that iterates as long as its given condition
(which must have type <code>bool</code>) evaluates to <code>true</code>. Inside a loop, the
keyword <code>break</code> aborts the loop, and <code>continue</code> aborts the current
iteration and continues with the next.</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">cake_amount</span> <span class="op">=</span> <span class="number">8</span>;
<span class="kw">while</span> <span class="ident">cake_amount</span> <span class="op">&gt;</span> <span class="number">0</span> {
    <span class="ident">cake_amount</span> <span class="op">-=</span> <span class="number">1</span>;
}
</pre>

<p><code>loop</code> denotes an infinite loop, and is the preferred way of writing <code>while true</code>:</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">x</span> <span class="op">=</span> <span class="number">5u</span>;
<span class="kw">loop</span> {
    <span class="ident">x</span> <span class="op">+=</span> <span class="ident">x</span> <span class="op">-</span> <span class="number">3</span>;
    <span class="kw">if</span> <span class="ident">x</span> <span class="op">%</span> <span class="number">5</span> <span class="op">==</span> <span class="number">0</span> { <span class="kw">break</span>; }
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>);
}
</pre>

<p>This code prints out a weird sequence of numbers and stops as soon as
it finds one that can be divided by five.</p>

<p>There is also a for-loop that can be used to iterate over a range of numbers:</p>
<pre class="rust "><span class="kw">for</span> <span class="ident">n</span> <span class="kw">in</span> <span class="ident">range</span>(<span class="number">0</span>, <span class="number">5</span>) {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">n</span>);
}
</pre>

<p>The snippet above prints integer numbers under 5 starting at 0.</p>

<p>More generally, a for loop works with anything implementing the <code>Iterator</code> trait.
Data structures can provide one or more methods that return iterators over
their contents. For example, strings support iteration over their contents in
various ways:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">s</span> <span class="op">=</span> <span class="string">"Hello"</span>;
<span class="kw">for</span> <span class="ident">c</span> <span class="kw">in</span> <span class="ident">s</span>.<span class="ident">chars</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">c</span>);
}
</pre>

<p>The snippet above prints the characters in "Hello" vertically, adding a new
line after each character.</p>

<h1 id="data-structures" class="section-header"><a href="#data-structures">5 Data structures(数据结构)</a></h1>
<h2 id="structs" class="section-header"><a href="#structs">5.1 Structs(结构)</a></h2>
<p>Rust struct types must be declared before they are used using the <code>struct</code>
syntax: <code>struct Name { field1: T1, field2: T2 [, ...] }</code>, where <code>T1</code>, <code>T2</code>,
... denote types. To construct a struct, use the same syntax, but leave off
the <code>struct</code>: for example: <code>Point { x: 1.0, y: 2.0 }</code>.</p>

<p>Structs are quite similar to C structs and are even laid out the same way in
memory (so you can read from a Rust struct in C, and vice-versa). Use the dot
operator to access struct fields, as in <code>mypoint.x</code>.</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">Point</span> {
    <span class="ident">x</span>: <span class="ident">f64</span>,
    <span class="ident">y</span>: <span class="ident">f64</span>
}
</pre>

<p>Structs have "inherited mutability", which means that any field of a struct
may be mutable, if the struct is in a mutable slot.</p>

<p>With a value (say, <code>mypoint</code>) of such a type in a mutable location, you can do
<code>mypoint.y += 1.0</code>. But in an immutable location, such an assignment to a
struct without inherited mutability would result in a type error.</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">mypoint</span> <span class="op">=</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">1.0</span>, <span class="ident">y</span>: <span class="number">1.0</span> };
<span class="kw">let</span> <span class="ident">origin</span> <span class="op">=</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">0.0</span>, <span class="ident">y</span>: <span class="number">0.0</span> };

<span class="ident">mypoint</span>.<span class="ident">y</span> <span class="op">+=</span> <span class="number">1.0</span>;<span class="comment"> // `mypoint` is mutable, and its fields as well
</span><span class="ident">origin</span>.<span class="ident">y</span> <span class="op">+=</span> <span class="number">1.0</span>;<span class="comment"> // ERROR: assigning to immutable field
</span></pre>

<p><code>match</code> patterns destructure structs. The basic syntax is
<code>Name { fieldname: pattern, ... }</code>:</p>
<pre class="rust "><span class="kw">match</span> <span class="ident">mypoint</span> {
    <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">0.0</span>, <span class="ident">y</span>: <span class="ident">yy</span> } <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">yy</span>),
    <span class="ident">Point</span> { <span class="ident">x</span>: <span class="ident">xx</span>,  <span class="ident">y</span>: <span class="ident">yy</span> } <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{} {}"</span>, <span class="ident">xx</span>, <span class="ident">yy</span>)
}
</pre>

<p>In general, the field names of a struct do not have to appear in the same
order they appear in the type. When you are not interested in all
the fields of a struct, a struct pattern may end with <code>, ..</code> (as in
<code>Name { field1, .. }</code>) to indicate that you're ignoring all other fields.
Additionally, struct fields have a shorthand matching form that simply
reuses the field name as the binding name.</p>
<pre class="rust "><span class="kw">match</span> <span class="ident">mypoint</span> {
    <span class="ident">Point</span> { <span class="ident">x</span>, .. } <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>)
}
</pre>

<h2 id="enums" class="section-header"><a href="#enums">5.2 Enums(枚举)</a></h2>
<p>Enums are datatypes with several alternate representations. A simple <code>enum</code>
defines one or more constants, all of which have the same type:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">Direction</span> {
    <span class="ident">North</span>,
    <span class="ident">East</span>,
    <span class="ident">South</span>,
    <span class="ident">West</span>
}
</pre>

<p>Each variant of this enum has a unique and constant integral discriminator
value. If no explicit discriminator is specified for a variant, the value
defaults to the value of the previous variant plus one. If the first variant
does not have a discriminator, it defaults to 0. For example, the value of
<code>North</code> is 0, <code>East</code> is 1, <code>South</code> is 2, and <code>West</code> is 3.</p>

<p>When an enum has simple integer discriminators, you can apply the <code>as</code> cast
operator to convert a variant to its discriminator value as an <code>int</code>:</p>
<pre class="rust "><span class="macro">println</span><span class="macro">!</span>( <span class="string">"{:?} =&gt; {}"</span>, <span class="ident">North</span>, <span class="ident">North</span> <span class="kw">as</span> <span class="ident">int</span> );
</pre>

<p>It is possible to set the discriminator values to chosen constant values:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">Color</span> {
  <span class="ident">Red</span> <span class="op">=</span> <span class="number">0xff0000</span>,
  <span class="ident">Green</span> <span class="op">=</span> <span class="number">0x00ff00</span>,
  <span class="ident">Blue</span> <span class="op">=</span> <span class="number">0x0000ff</span>
}
</pre>

<p>Variants do not have to be simple values; they may be more complex:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">Shape</span> {
    <span class="ident">Circle</span>(<span class="ident">Point</span>, <span class="ident">f64</span>),
    <span class="ident">Rectangle</span>(<span class="ident">Point</span>, <span class="ident">Point</span>)
}
</pre>

<p>A value of this type is either a <code>Circle</code>, in which case it contains a
<code>Point</code> struct and a f64, or a <code>Rectangle</code>, in which case it contains
two <code>Point</code> structs. The run-time representation of such a value
includes an identifier of the actual form that it holds, much like the
"tagged union" pattern in C, but with better static guarantees.</p>

<p>This declaration defines a type <code>Shape</code> that can refer to such shapes, and two
functions, <code>Circle</code> and <code>Rectangle</code>, which can be used to construct values of
the type. To create a new Circle, write <code>Circle(Point { x: 0.0, y: 0.0 },
10.0)</code>.</p>

<p>All of these variant constructors may be used as patterns. The only way to
access the contents of an enum instance is the destructuring of a match. For
example:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>;
<span class="kw">fn</span> <span class="ident">area</span>(<span class="ident">sh</span>: <span class="ident">Shape</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {
    <span class="kw">match</span> <span class="ident">sh</span> {
        <span class="ident">Circle</span>(_, <span class="ident">size</span>) <span class="op">=&gt;</span> <span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span> <span class="op">*</span> <span class="ident">size</span> <span class="op">*</span> <span class="ident">size</span>,
        <span class="ident">Rectangle</span>(<span class="ident">Point</span> { <span class="ident">x</span>, <span class="ident">y</span> }, <span class="ident">Point</span> { <span class="ident">x</span>: <span class="ident">x2</span>, <span class="ident">y</span>: <span class="ident">y2</span> }) <span class="op">=&gt;</span> (<span class="ident">x2</span> <span class="op">-</span> <span class="ident">x</span>) <span class="op">*</span> (<span class="ident">y2</span> <span class="op">-</span> <span class="ident">y</span>)
    }
}
</pre>

<p>Use a lone <code>_</code> to ignore an individual field. Ignore all fields of a variant
like: <code>Circle(..)</code>. Nullary enum patterns are written without parentheses:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">point_from_direction</span>(<span class="ident">dir</span>: <span class="ident">Direction</span>) <span class="op">-&gt;</span> <span class="ident">Point</span> {
    <span class="kw">match</span> <span class="ident">dir</span> {
        <span class="ident">North</span> <span class="op">=&gt;</span> <span class="ident">Point</span> { <span class="ident">x</span>:  <span class="number">0.0</span>, <span class="ident">y</span>:  <span class="number">1.0</span> },
        <span class="ident">East</span>  <span class="op">=&gt;</span> <span class="ident">Point</span> { <span class="ident">x</span>:  <span class="number">1.0</span>, <span class="ident">y</span>:  <span class="number">0.0</span> },
        <span class="ident">South</span> <span class="op">=&gt;</span> <span class="ident">Point</span> { <span class="ident">x</span>:  <span class="number">0.0</span>, <span class="ident">y</span>: <span class="op">-</span><span class="number">1.0</span> },
        <span class="ident">West</span>  <span class="op">=&gt;</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="op">-</span><span class="number">1.0</span>, <span class="ident">y</span>:  <span class="number">0.0</span> }
    }
}
</pre>

<p>Enum variants may also be structs. For example:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>;
<span class="kw">enum</span> <span class="ident">Shape</span> {
    <span class="ident">Circle</span> { <span class="ident">center</span>: <span class="ident">Point</span>, <span class="ident">radius</span>: <span class="ident">f64</span> },
    <span class="ident">Rectangle</span> { <span class="ident">top_left</span>: <span class="ident">Point</span>, <span class="ident">bottom_right</span>: <span class="ident">Point</span> }
}
<span class="kw">fn</span> <span class="ident">area</span>(<span class="ident">sh</span>: <span class="ident">Shape</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {
    <span class="kw">match</span> <span class="ident">sh</span> {
        <span class="ident">Circle</span> { <span class="ident">radius</span>: <span class="ident">radius</span>, .. } <span class="op">=&gt;</span> <span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span> <span class="op">*</span> <span class="ident">square</span>(<span class="ident">radius</span>),
        <span class="ident">Rectangle</span> { <span class="ident">top_left</span>: <span class="ident">top_left</span>, <span class="ident">bottom_right</span>: <span class="ident">bottom_right</span> } <span class="op">=&gt;</span> {
            (<span class="ident">bottom_right</span>.<span class="ident">x</span> <span class="op">-</span> <span class="ident">top_left</span>.<span class="ident">x</span>) <span class="op">*</span> (<span class="ident">top_left</span>.<span class="ident">y</span> <span class="op">-</span> <span class="ident">bottom_right</span>.<span class="ident">y</span>)
        }
    }
}
</pre>

<blockquote>
<p><em>Note:</em> This feature of the compiler is currently gated behind the
<code>#[feature(struct_variant)]</code> directive. More about these directives can be
found in the manual.</p>
</blockquote>

<h2 id="tuples" class="section-header"><a href="#tuples">5.3 Tuples(元组)</a></h2>
<p>Tuples in Rust behave exactly like structs, except that their fields do not
have names. Thus, you cannot access their fields with dot notation.  Tuples
can have any arity (number of elements) except for 0 (though you may consider
unit, <code>()</code>, as the empty tuple if you like).</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">mytup</span>: (<span class="ident">int</span>, <span class="ident">int</span>, <span class="ident">f64</span>) <span class="op">=</span> (<span class="number">10</span>, <span class="number">20</span>, <span class="number">30.0</span>);
<span class="kw">match</span> <span class="ident">mytup</span> {
  (<span class="ident">a</span>, <span class="ident">b</span>, <span class="ident">c</span>) <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">a</span> <span class="op">+</span> <span class="ident">b</span> <span class="op">+</span> (<span class="ident">c</span> <span class="kw">as</span> <span class="ident">int</span>))
}
</pre>

<h2 id="tuple-structs" class="section-header"><a href="#tuple-structs">5.4 Tuple structs(元组结构)</a></h2>
<p>Rust also has <em>tuple structs</em>, which behave like both structs and tuples,
except that, unlike tuples, tuple structs have names (so <code>Foo(1, 2)</code> has a
different type from <code>Bar(1, 2)</code>), and tuple structs' <em>fields</em> do not have
names.</p>

<p>For example:</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">MyTup</span>(<span class="ident">int</span>, <span class="ident">int</span>, <span class="ident">f64</span>);
<span class="kw">let</span> <span class="ident">mytup</span>: <span class="ident">MyTup</span> <span class="op">=</span> <span class="ident">MyTup</span>(<span class="number">10</span>, <span class="number">20</span>, <span class="number">30.0</span>);
<span class="kw">match</span> <span class="ident">mytup</span> {
  <span class="ident">MyTup</span>(<span class="ident">a</span>, <span class="ident">b</span>, <span class="ident">c</span>) <span class="op">=&gt;</span> <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">a</span> <span class="op">+</span> <span class="ident">b</span> <span class="op">+</span> (<span class="ident">c</span> <span class="kw">as</span> <span class="ident">int</span>))
}
</pre>

<p><a name="newtype"></a></p>

<p>There is a special case for tuple structs with a single field, which are
sometimes called "newtypes" (after Haskell's "newtype" feature). These are
used to define new types in such a way that the new name is not just a
synonym for an existing type but is rather its own distinct type.</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">GizmoId</span>(<span class="ident">int</span>);
</pre>

<p>Types like this can be useful to differentiate between data that have
the same underlying type but must be used in different ways.</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">Inches</span>(<span class="ident">int</span>);
<span class="kw">struct</span> <span class="ident">Centimeters</span>(<span class="ident">int</span>);
</pre>

<p>The above definitions allow for a simple way for programs to avoid
confusing numbers that correspond to different units. Their integer
values can be extracted with pattern matching:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">length_with_unit</span> <span class="op">=</span> <span class="ident">Inches</span>(<span class="number">10</span>);
<span class="kw">let</span> <span class="ident">Inches</span>(<span class="ident">integer_length</span>) <span class="op">=</span> <span class="ident">length_with_unit</span>;
<span class="macro">println</span><span class="macro">!</span>(<span class="string">"length is {} inches"</span>, <span class="ident">integer_length</span>);
</pre>

<h1 id="functions" class="section-header"><a href="#functions">6 Functions(函数)</a></h1>
<p>We've already seen several function definitions. Like all other static
declarations, such as <code>type</code>, functions can be declared both at the
top level and inside other functions (or in modules, which we'll come
back to <a href="#crates-and-the-module-system">later</a>). The <code>fn</code> keyword introduces a
function. A function has an argument list, which is a parenthesized
list of <code>name: type</code> pairs separated by commas. An arrow <code>-&gt;</code>
separates the argument list and the function's return type.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">line</span>(<span class="ident">a</span>: <span class="ident">int</span>, <span class="ident">b</span>: <span class="ident">int</span>, <span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
    <span class="kw">return</span> <span class="ident">a</span> <span class="op">*</span> <span class="ident">x</span> <span class="op">+</span> <span class="ident">b</span>;
}
</pre>

<p>The <code>return</code> keyword immediately returns from the body of a function. It
is optionally followed by an expression to return. A function can
also return a value by having its top-level block produce an
expression.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">line</span>(<span class="ident">a</span>: <span class="ident">int</span>, <span class="ident">b</span>: <span class="ident">int</span>, <span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> {
    <span class="ident">a</span> <span class="op">*</span> <span class="ident">x</span> <span class="op">+</span> <span class="ident">b</span>
}
</pre>

<p>It's better Rust style to write a return value this way instead of
writing an explicit <code>return</code>. The utility of <code>return</code> comes in when
returning early from a function. Functions that do not return a value
are said to return unit, <code>()</code>, and both the return type and the return
value may be omitted from the definition. The following two functions
are equivalent.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">do_nothing_the_hard_way</span>() <span class="op">-&gt;</span> () { <span class="kw">return</span> (); }

<span class="kw">fn</span> <span class="ident">do_nothing_the_easy_way</span>() { }
</pre>

<p>Ending the function with a semicolon like so is equivalent to returning <code>()</code>.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">line</span>(<span class="ident">a</span>: <span class="ident">int</span>, <span class="ident">b</span>: <span class="ident">int</span>, <span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="ident">a</span> <span class="op">*</span> <span class="ident">x</span> <span class="op">+</span> <span class="ident">b</span>  }
<span class="kw">fn</span> <span class="ident">oops</span>(<span class="ident">a</span>: <span class="ident">int</span>, <span class="ident">b</span>: <span class="ident">int</span>, <span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> ()  { <span class="ident">a</span> <span class="op">*</span> <span class="ident">x</span> <span class="op">+</span> <span class="ident">b</span>; }

<span class="macro">assert</span><span class="macro">!</span>(<span class="number">8</span> <span class="op">==</span> <span class="ident">line</span>(<span class="number">5</span>, <span class="number">3</span>, <span class="number">1</span>));
<span class="macro">assert</span><span class="macro">!</span>(() <span class="op">==</span> <span class="ident">oops</span>(<span class="number">5</span>, <span class="number">3</span>, <span class="number">1</span>));
</pre>

<p>As with <code>match</code> expressions and <code>let</code> bindings, function arguments support
pattern destructuring. Like <code>let</code>, argument patterns must be irrefutable,
as in this example that unpacks the first value from a tuple and returns it.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">first</span>((<span class="ident">value</span>, _): (<span class="ident">int</span>, <span class="ident">f64</span>)) <span class="op">-&gt;</span> <span class="ident">int</span> { <span class="ident">value</span> }
</pre>

<h1 id="destructors" class="section-header"><a href="#destructors">7 Destructors(解构器)</a></h1>
<p>A <em>destructor</em> is a function responsible for cleaning up the resources used by
an object when it is no longer accessible. Destructors can be defined to handle
the release of resources like files, sockets and heap memory.</p>

<p>Objects are never accessible after their destructor has been called, so no
dynamic failures are possible from accessing freed resources. When a task
fails, destructors of all objects in the task are called.</p>

<p>The <code>box</code> operator performs memory allocation on the heap:</p>
<pre class="rust ">{<span class="comment">
    // an integer allocated on the heap
    </span><span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">10</span>;
}<span class="comment">
// the destructor frees the heap memory as soon as `y` goes out of scope
</span></pre>

<p>Rust includes syntax for heap memory allocation in the language since it's
commonly used, but the same semantics can be implemented by a type with a
custom destructor.</p>

<h1 id="ownership" class="section-header"><a href="#ownership">8 Ownership(所有权)</a></h1>
<p>Rust formalizes the concept of object ownership to delegate management of an
object's lifetime to either a variable or a task-local garbage collector. An
object's owner is responsible for managing the lifetime of the object by
calling the destructor, and the owner determines whether the object is mutable.</p>

<p>Ownership is recursive, so mutability is inherited recursively and a destructor
destroys the contained tree of owned objects. Variables are top-level owners
and destroy the contained object when they go out of scope.</p>
<pre class="rust "><span class="comment">// the struct owns the objects contained in the `x` and `y` fields
</span><span class="kw">struct</span> <span class="ident">Foo</span> { <span class="ident">x</span>: <span class="ident">int</span>, <span class="ident">y</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> }

{<span class="comment">
    // `a` is the owner of the struct, and thus the owner of the struct's fields
    </span><span class="kw">let</span> <span class="ident">a</span> <span class="op">=</span> <span class="ident">Foo</span> { <span class="ident">x</span>: <span class="number">5</span>, <span class="ident">y</span>: <span class="kw">box</span> <span class="number">10</span> };
}<span class="comment">
// when `a` goes out of scope, the destructor for the `~int` in the struct's
// field is called

// `b` is mutable, and the mutability is inherited by the objects it owns
</span><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">b</span> <span class="op">=</span> <span class="ident">Foo</span> { <span class="ident">x</span>: <span class="number">5</span>, <span class="ident">y</span>: <span class="kw">box</span> <span class="number">10</span> };
<span class="ident">b</span>.<span class="ident">x</span> <span class="op">=</span> <span class="number">10</span>;
</pre>

<p>If an object doesn't contain any non-Send types, it consists of a single
ownership tree and is itself given the <code>Send</code> trait which allows it to be sent
between tasks. Custom destructors can only be implemented directly on types
that are <code>Send</code>, but non-<code>Send</code> types can still <em>contain</em> types with custom
destructors. Example of types which are not <code>Send</code> are <a href="http://static.rust-lang.org/doc/master/std/gc/struct.Gc.html"><code>Gc&lt;T&gt;</code></a> and
<a href="http://static.rust-lang.org/doc/master/std/rc/struct.Rc.html"><code>Rc&lt;T&gt;</code></a>, the shared-ownership types.</p>

<h1 id="implementing-a-linked-list" class="section-header"><a href="#implementing-a-linked-list">9 Implementing a linked list(实现链接表)</a></h1>
<p>An <code>enum</code> is a natural fit for describing a linked list, because it can express
a <code>List</code> type as being <em>either</em> the end of the list (<code>Nil</code>) or another node
(<code>Cons</code>). The full definition of the <code>Cons</code> variant will require some thought.</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">List</span> {
    <span class="ident">Cons</span>(...),<span class="comment"> // an incomplete definition of the next element in a List
    </span><span class="ident">Nil</span><span class="comment">        // the end of a List
</span>}
</pre>

<p>The obvious approach is to define <code>Cons</code> as containing an element in the list
along with the next <code>List</code> node. However, this will generate a compiler error.</p>
<pre class="rust "><span class="comment">// error: illegal recursive enum type; wrap the inner value in a box to make it
// representable
</span><span class="kw">enum</span> <span class="ident">List</span> {
    <span class="ident">Cons</span>(<span class="ident">u32</span>, <span class="ident">List</span>),<span class="comment"> // an element (`u32`) and the next node in the list
    </span><span class="ident">Nil</span>
}
</pre>

<p>This error message is related to Rust's precise control over memory layout, and
solving it will require introducing the concept of <em>boxing</em>.</p>

<h2 id="boxes" class="section-header"><a href="#boxes">9.1 Boxes(封装)</a></h2>
<p>A value in Rust is stored directly inside the owner. If a <code>struct</code> contains
four <code>u32</code> fields, it will be four times as large as a single <code>u32</code>.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">mem</span>::<span class="ident">size_of</span>;<span class="comment"> // bring `size_of` into the current scope, for convenience

</span><span class="kw">struct</span> <span class="ident">Foo</span> {
    <span class="ident">a</span>: <span class="ident">u32</span>,
    <span class="ident">b</span>: <span class="ident">u32</span>,
    <span class="ident">c</span>: <span class="ident">u32</span>,
    <span class="ident">d</span>: <span class="ident">u32</span>
}

<span class="macro">assert_eq</span><span class="macro">!</span>(<span class="ident">size_of</span>::<span class="op">&lt;</span><span class="ident">Foo</span><span class="op">&gt;</span>(), <span class="ident">size_of</span>::<span class="op">&lt;</span><span class="ident">u32</span><span class="op">&gt;</span>() <span class="op">*</span> <span class="number">4</span>);

<span class="kw">struct</span> <span class="ident">Bar</span> {
    <span class="ident">a</span>: <span class="ident">Foo</span>,
    <span class="ident">b</span>: <span class="ident">Foo</span>,
    <span class="ident">c</span>: <span class="ident">Foo</span>,
    <span class="ident">d</span>: <span class="ident">Foo</span>
}

<span class="macro">assert_eq</span><span class="macro">!</span>(<span class="ident">size_of</span>::<span class="op">&lt;</span><span class="ident">Bar</span><span class="op">&gt;</span>(), <span class="ident">size_of</span>::<span class="op">&lt;</span><span class="ident">u32</span><span class="op">&gt;</span>() <span class="op">*</span> <span class="number">16</span>);
</pre>

<p>Our previous attempt at defining the <code>List</code> type included an <code>u32</code> and a <code>List</code>
directly inside <code>Cons</code>, making it at least as big as the sum of both types. The
type was invalid because the size was infinite!</p>

<p>An <em>owned box</em> (<code>Box</code>, located in the <code>std::owned</code> module) uses a dynamic memory
allocation to provide the invariant of always being the size of a pointer,
regardless of the contained type. This can be leveraged to create a valid <code>List</code>
definition:</p>
<pre class="rust ">
<span class="kw">enum</span> <span class="ident">List</span> {
    <span class="ident">Cons</span>(<span class="ident">u32</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&gt;</span>),
    <span class="ident">Nil</span>
}
</pre>

<p>Defining a recursive data structure like this is the canonical example of an
owned box. Much like an unboxed value, an owned box has a single owner and is
therefore limited to expressing a tree-like data structure.</p>

<p>Consider an instance of our <code>List</code> type:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">list</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">1</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">2</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">3</span>, <span class="kw">box</span> <span class="ident">Nil</span>)));
</pre>

<p>It represents an owned tree of values, inheriting mutability down the tree and
being destroyed along with the owner. Since the <code>list</code> variable above is
immutable, the whole list is immutable. The memory allocation itself is the
box, while the owner holds onto a pointer to it:</p>

<pre><code class="language-{.notrust}">            List box            List box            List box          List box
        +--------------+    +--------------+    +--------------+    +----------+
list -&gt; | Cons | 1 |   | -&gt; | Cons | 2 |   | -&gt; | Cons | 3 |   | -&gt; | Nil      |
        +--------------+    +--------------+    +--------------+    +----------+</code></pre>

<blockquote>
<p><em>Note:</em> the above diagram shows the logical contents of the enum. The actual
memory layout of the enum may vary. For example, for the <code>List</code> enum shown
above, Rust guarantees that there will be no enum tag field in the actual
structure. See the language reference for more details.</p>
</blockquote>

<p>An owned box is a common example of a type with a destructor. The allocated
memory is cleaned up when the box is destroyed.</p>

<h2 id="move-semantics" class="section-header"><a href="#move-semantics">9.2 Move semantics(Move语义)</a></h2>
<p>Rust uses a shallow copy for parameter passing, assignment and returning from
functions. Passing around the <code>List</code> will copy only as deep as the pointer to
the box rather than doing an implicit heap allocation.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">1</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">2</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">3</span>, <span class="kw">box</span> <span class="ident">Nil</span>)));
<span class="kw">let</span> <span class="ident">ys</span> <span class="op">=</span> <span class="ident">xs</span>;<span class="comment"> // copies `Cons(u32, pointer)` shallowly
</span></pre>

<p>Rust will consider a shallow copy of a type with a destructor like <code>List</code> to
<em>move ownership</em> of the value. After a value has been moved, the source
location cannot be used unless it is reinitialized.</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Nil</span>;
<span class="kw">let</span> <span class="ident">ys</span> <span class="op">=</span> <span class="ident">xs</span>;<span class="comment">

// attempting to use `xs` will result in an error here

</span><span class="ident">xs</span> <span class="op">=</span> <span class="ident">Nil</span>;<span class="comment">

// `xs` can be used again
</span></pre>

<p>A destructor call will only occur for a variable that has not been moved from,
as it is only called a single time.</p>

<p>Avoiding a move can be done with the library-defined <code>clone</code> method:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">5</span>;
<span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="ident">x</span>.<span class="ident">clone</span>();<span class="comment"> // `y` is a newly allocated box
</span><span class="kw">let</span> <span class="ident">z</span> <span class="op">=</span> <span class="ident">x</span>;<span class="comment"> // no new memory allocated, `x` can no longer be used
</span></pre>

<p>The <code>clone</code> method is provided by the <code>Clone</code> trait, and can be derived for
our <code>List</code> type. Traits will be explained in detail <a href="#traits">later</a>.</p>
<pre class="rust "><span class="attribute">#[<span class="ident">deriving</span>(<span class="ident">Clone</span>)]</span>
<span class="kw">enum</span> <span class="ident">List</span> {
    <span class="ident">Cons</span>(<span class="ident">u32</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&gt;</span>),
    <span class="ident">Nil</span>
}

<span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">5</span>, <span class="kw">box</span> <span class="ident">Nil</span>);
<span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="ident">x</span>.<span class="ident">clone</span>();<span class="comment">

// `x` can still be used!

</span><span class="kw">let</span> <span class="ident">z</span> <span class="op">=</span> <span class="ident">x</span>;<span class="comment">

// and now, it can no longer be used since it has been moved
</span></pre>

<p>The mutability of a value may be changed by moving it to a new owner:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">r</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">13</span>;
<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">s</span> <span class="op">=</span> <span class="ident">r</span>;<span class="comment"> // box becomes mutable
</span><span class="op">*</span><span class="ident">s</span> <span class="op">+=</span> <span class="number">1</span>;
<span class="kw">let</span> <span class="ident">t</span> <span class="op">=</span> <span class="ident">s</span>;<span class="comment"> // box becomes immutable
</span></pre>

<p>A simple way to define a function prepending to the <code>List</code> type is to take
advantage of moves:</p>
<pre class="rust "><span class="kw">enum</span> <span class="ident">List</span> {
    <span class="ident">Cons</span>(<span class="ident">u32</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&gt;</span>),
    <span class="ident">Nil</span>
}

<span class="kw">fn</span> <span class="ident">prepend</span>(<span class="ident">xs</span>: <span class="ident">List</span>, <span class="ident">value</span>: <span class="ident">u32</span>) <span class="op">-&gt;</span> <span class="ident">List</span> {
    <span class="ident">Cons</span>(<span class="ident">value</span>, <span class="kw">box</span> <span class="ident">xs</span>)
}

<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Nil</span>;
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>(<span class="ident">xs</span>, <span class="number">1</span>);
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>(<span class="ident">xs</span>, <span class="number">2</span>);
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>(<span class="ident">xs</span>, <span class="number">3</span>);
</pre>

<p>However, this is not a very flexible definition of <code>prepend</code> as it requires
ownership of a list to be passed in rather than just mutating it in-place.</p>

<h2 id="references" class="section-header"><a href="#references">9.3 References(参考)</a></h2>
<p>The obvious signature for a <code>List</code> equality comparison is the following:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">eq</span>(<span class="ident">xs</span>: <span class="ident">List</span>, <span class="ident">ys</span>: <span class="ident">List</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment"> /* ... */ </span>}
</pre>

<p>However, this will cause both lists to be moved into the function. Ownership
isn't required to compare the lists, so the function should take <em>references</em>
(&amp;T) instead.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">eq</span>(<span class="ident">xs</span>: <span class="kw-2">&amp;</span><span class="ident">List</span>, <span class="ident">ys</span>: <span class="kw-2">&amp;</span><span class="ident">List</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment"> /* ... */ </span>}
</pre>

<p>A reference is a <em>non-owning</em> view of a value. A reference can be obtained with the <code>&amp;</code> (address-of)
operator. It can be dereferenced by using the <code>*</code> operator. In a pattern, such as <code>match</code> expression
branches, the <code>ref</code> keyword can be used to bind to a variable name by-reference rather than
by-value. A recursive definition of equality using references is as follows:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">eq</span>(<span class="ident">xs</span>: <span class="kw-2">&amp;</span><span class="ident">List</span>, <span class="ident">ys</span>: <span class="kw-2">&amp;</span><span class="ident">List</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment">
    // Match on the next node in both lists.
    </span><span class="kw">match</span> (<span class="ident">xs</span>, <span class="ident">ys</span>) {<span class="comment">
        // If we have reached the end of both lists, they are equal.
        </span>(<span class="kw-2">&amp;</span><span class="ident">Nil</span>, <span class="kw-2">&amp;</span><span class="ident">Nil</span>) <span class="op">=&gt;</span> <span class="boolval">true</span>,<span class="comment">
        // If the current elements of both lists are equal, keep going.
        </span>(<span class="kw-2">&amp;</span><span class="ident">Cons</span>(<span class="ident">x</span>, <span class="kw">box</span> <span class="kw-2">ref</span> <span class="ident">next_xs</span>), <span class="kw-2">&amp;</span><span class="ident">Cons</span>(<span class="ident">y</span>, <span class="kw">box</span> <span class="kw-2">ref</span> <span class="ident">next_ys</span>))
                <span class="kw">if</span> <span class="ident">x</span> <span class="op">==</span> <span class="ident">y</span> <span class="op">=&gt;</span> <span class="ident">eq</span>(<span class="ident">next_xs</span>, <span class="ident">next_ys</span>),<span class="comment">
        // If the current elements are not equal, the lists are not equal.
        </span>_ <span class="op">=&gt;</span> <span class="boolval">false</span>
    }
}

<span class="kw">let</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">5</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">10</span>, <span class="kw">box</span> <span class="ident">Nil</span>));
<span class="kw">let</span> <span class="ident">ys</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">5</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">10</span>, <span class="kw">box</span> <span class="ident">Nil</span>));
<span class="macro">assert</span><span class="macro">!</span>(<span class="ident">eq</span>(<span class="kw-2">&amp;</span><span class="ident">xs</span>, <span class="kw-2">&amp;</span><span class="ident">ys</span>));
</pre>

<blockquote>
<p><em>Note:</em> Rust doesn't guarantee <a href="http://en.wikipedia.org/wiki/Tail_call">tail-call</a> optimization,
but LLVM is able to handle a simple case like this with optimizations enabled.</p>
</blockquote>

<h2 id="lists-of-other-types" class="section-header"><a href="#lists-of-other-types">9.4 Lists of other types(其他类型列表)</a></h2>
<p>Our <code>List</code> type is currently always a list of 32-bit unsigned integers. By
leveraging Rust's support for generics, it can be extended to work for any
element type.</p>

<p>The <code>u32</code> in the previous definition can be substituted with a type parameter:</p>

<blockquote>
<p><em>Note:</em> The following code introduces generics, which are explained in a
<a href="#generics">dedicated section</a>.</p>
</blockquote>
<pre class="rust "><span class="kw">enum</span> <span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="ident">Cons</span>(<span class="ident">T</span>, <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;&gt;</span>),
    <span class="ident">Nil</span>
}
</pre>

<p>The old <code>List</code> of <code>u32</code> is now available as <code>List&lt;u32&gt;</code>. The <code>prepend</code>
definition has to be updated too:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">prepend</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>(<span class="ident">xs</span>: <span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>, <span class="ident">value</span>: <span class="ident">T</span>) <span class="op">-&gt;</span> <span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="ident">Cons</span>(<span class="ident">value</span>, <span class="kw">box</span> <span class="ident">xs</span>)
}
</pre>

<p>Generic functions and types like this are equivalent to defining specialized
versions for each set of type parameters.</p>

<p>Using the generic <code>List&lt;T&gt;</code> works much like before, thanks to type inference:</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Nil</span>;<span class="comment"> // Unknown type! This is a `List&lt;T&gt;`, but `T` can be anything.
</span><span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>(<span class="ident">xs</span>, <span class="number">10</span>);<span class="comment"> // Here the compiler infers `xs`'s type as `List&lt;int&gt;`.
</span><span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>(<span class="ident">xs</span>, <span class="number">15</span>);
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>(<span class="ident">xs</span>, <span class="number">20</span>);
</pre>

<p>The code sample above demonstrates type inference making most type annotations optional. It is
equivalent to the following type-annotated code:</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">xs</span>: <span class="ident">List</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">Nil</span>::<span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span>;
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>::<span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span>(<span class="ident">xs</span>, <span class="number">10</span>);
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>::<span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span>(<span class="ident">xs</span>, <span class="number">15</span>);
<span class="ident">xs</span> <span class="op">=</span> <span class="ident">prepend</span>::<span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span>(<span class="ident">xs</span>, <span class="number">20</span>);
</pre>

<p>In declarations, the language uses <code>Type&lt;T, U, V&gt;</code> to describe a list of type
parameters, but expressions use <code>identifier::&lt;T, U, V&gt;</code>, to disambiguate the
<code>&lt;</code> operator.</p>

<h2 id="defining-list-equality-with-generics" class="section-header"><a href="#defining-list-equality-with-generics">9.5 Defining list equality with generics(用泛型定义列表)</a></h2>
<p>Generic functions are type-checked from the definition, so any necessary properties of the type must
be specified up-front. Our previous definition of list equality relied on the element type having
the <code>==</code> operator available, and took advantage of the lack of a destructor on <code>u32</code> to copy it
without a move of ownership.</p>

<p>We can add a <em>trait bound</em> on the <code>Eq</code> trait to require that the type implement the <code>==</code> operator.
Two more <code>ref</code> annotations need to be added to avoid attempting to move out the element types:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">eq</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Eq</span><span class="op">&gt;</span>(<span class="ident">xs</span>: <span class="kw-2">&amp;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>, <span class="ident">ys</span>: <span class="kw-2">&amp;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment">
    // Match on the next node in both lists.
    </span><span class="kw">match</span> (<span class="ident">xs</span>, <span class="ident">ys</span>) {<span class="comment">
        // If we have reached the end of both lists, they are equal.
        </span>(<span class="kw-2">&amp;</span><span class="ident">Nil</span>, <span class="kw-2">&amp;</span><span class="ident">Nil</span>) <span class="op">=&gt;</span> <span class="boolval">true</span>,<span class="comment">
        // If the current elements of both lists are equal, keep going.
        </span>(<span class="kw-2">&amp;</span><span class="ident">Cons</span>(<span class="kw-2">ref</span> <span class="ident">x</span>, <span class="kw">box</span> <span class="kw-2">ref</span> <span class="ident">next_xs</span>), <span class="kw-2">&amp;</span><span class="ident">Cons</span>(<span class="kw-2">ref</span> <span class="ident">y</span>, <span class="kw">box</span> <span class="kw-2">ref</span> <span class="ident">next_ys</span>))
                <span class="kw">if</span> <span class="ident">x</span> <span class="op">==</span> <span class="ident">y</span> <span class="op">=&gt;</span> <span class="ident">eq</span>(<span class="ident">next_xs</span>, <span class="ident">next_ys</span>),<span class="comment">
        // If the current elements are not equal, the lists are not equal.
        </span>_ <span class="op">=&gt;</span> <span class="boolval">false</span>
    }
}

<span class="kw">let</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="string">'c'</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="string">'a'</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="string">'t'</span>, <span class="kw">box</span> <span class="ident">Nil</span>)));
<span class="kw">let</span> <span class="ident">ys</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="string">'c'</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="string">'a'</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="string">'t'</span>, <span class="kw">box</span> <span class="ident">Nil</span>)));
<span class="macro">assert</span><span class="macro">!</span>(<span class="ident">eq</span>(<span class="kw-2">&amp;</span><span class="ident">xs</span>, <span class="kw-2">&amp;</span><span class="ident">ys</span>));
</pre>

<p>This would be a good opportunity to implement the <code>Eq</code> trait for our list type, making the <code>==</code> and
<code>!=</code> operators available. We'll need to provide an <code>impl</code> for the <code>Eq</code> trait and a definition of the
<code>eq</code> method. In a method, the <code>self</code> parameter refers to an instance of the type we're implementing
on.</p>
<pre class="rust "><span class="kw">impl</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Eq</span><span class="op">&gt;</span> <span class="ident">Eq</span> <span class="kw">for</span> <span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="kw">fn</span> <span class="ident">eq</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">ys</span>: <span class="kw-2">&amp;</span><span class="ident">List</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> {<span class="comment">
        // Match on the next node in both lists.
        </span><span class="kw">match</span> (<span class="self">self</span>, <span class="ident">ys</span>) {<span class="comment">
            // If we have reached the end of both lists, they are equal.
            </span>(<span class="kw-2">&amp;</span><span class="ident">Nil</span>, <span class="kw-2">&amp;</span><span class="ident">Nil</span>) <span class="op">=&gt;</span> <span class="boolval">true</span>,<span class="comment">
            // If the current elements of both lists are equal, keep going.
            </span>(<span class="kw-2">&amp;</span><span class="ident">Cons</span>(<span class="kw-2">ref</span> <span class="ident">x</span>, <span class="kw">box</span> <span class="kw-2">ref</span> <span class="ident">next_xs</span>), <span class="kw-2">&amp;</span><span class="ident">Cons</span>(<span class="kw-2">ref</span> <span class="ident">y</span>, <span class="kw">box</span> <span class="kw-2">ref</span> <span class="ident">next_ys</span>))
                    <span class="kw">if</span> <span class="ident">x</span> <span class="op">==</span> <span class="ident">y</span> <span class="op">=&gt;</span> <span class="ident">next_xs</span> <span class="op">==</span> <span class="ident">next_ys</span>,<span class="comment">
            // If the current elements are not equal, the lists are not equal.
            </span>_ <span class="op">=&gt;</span> <span class="boolval">false</span>
        }
    }
}

<span class="kw">let</span> <span class="ident">xs</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">5</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">10</span>, <span class="kw">box</span> <span class="ident">Nil</span>));
<span class="kw">let</span> <span class="ident">ys</span> <span class="op">=</span> <span class="ident">Cons</span>(<span class="number">5</span>, <span class="kw">box</span> <span class="ident">Cons</span>(<span class="number">10</span>, <span class="kw">box</span> <span class="ident">Nil</span>));<span class="comment">
// The methods below are part of the Eq trait,
// which we implemented on our linked list.
</span><span class="macro">assert</span><span class="macro">!</span>(<span class="ident">xs</span>.<span class="ident">eq</span>(<span class="kw-2">&amp;</span><span class="ident">ys</span>));
<span class="macro">assert</span><span class="macro">!</span>(<span class="op">!</span><span class="ident">xs</span>.<span class="ident">ne</span>(<span class="kw-2">&amp;</span><span class="ident">ys</span>));<span class="comment">

// The Eq trait also allows us to use the shorthand infix operators.
</span><span class="macro">assert</span><span class="macro">!</span>(<span class="ident">xs</span> <span class="op">==</span> <span class="ident">ys</span>);<span class="comment">    // `xs == ys` is short for `xs.eq(&amp;ys)`
</span><span class="macro">assert</span><span class="macro">!</span>(<span class="op">!</span>(<span class="ident">xs</span> <span class="op">!=</span> <span class="ident">ys</span>));<span class="comment"> // `xs != ys` is short for `xs.ne(&amp;ys)`
</span></pre>

<h1 id="more-on-boxes" class="section-header"><a href="#more-on-boxes">10 More on boxes(更多有关封装)</a></h1>
<p>The most common use case for owned boxes is creating recursive data structures
like a binary search tree. Rust's trait-based generics system (covered later in
the tutorial) is usually used for static dispatch, but also provides dynamic
dispatch via boxing. Values of different types may have different sizes, but a
box is able to <em>erase</em> the difference via the layer of indirection they
provide.</p>

<p>In uncommon cases, the indirection can provide a performance gain or memory
reduction by making values smaller. However, unboxed values should almost
always be preferred when they are usable.</p>

<p>Note that returning large unboxed values via boxes is unnecessary. A large
value is returned via a hidden output parameter, and the decision on where to
place the return value should be left to the caller:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">foo</span>() <span class="op">-&gt;</span> (<span class="ident">u64</span>, <span class="ident">u64</span>, <span class="ident">u64</span>, <span class="ident">u64</span>, <span class="ident">u64</span>, <span class="ident">u64</span>) {
    (<span class="number">5</span>, <span class="number">5</span>, <span class="number">5</span>, <span class="number">5</span>, <span class="number">5</span>, <span class="number">5</span>)
}

<span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">foo</span>();<span class="comment"> // allocates a box, and writes the integers directly to it
</span></pre>

<p>Beyond the properties granted by the size, an owned box behaves as a regular
value by inheriting the mutability and lifetime of the owner:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="number">5</span>;<span class="comment"> // immutable
</span><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">y</span> <span class="op">=</span> <span class="number">5</span>;<span class="comment"> // mutable
</span><span class="ident">y</span> <span class="op">+=</span> <span class="number">2</span>;

<span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">5</span>;<span class="comment"> // immutable
</span><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">y</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">5</span>;<span class="comment"> // mutable
</span><span class="op">*</span><span class="ident">y</span> <span class="op">+=</span> <span class="number">2</span>;<span class="comment"> // the `*` operator is needed to access the contained value
</span></pre>

<h1 id="references-1" class="section-header"><a href="#references-1">11 References(引用)</a></h1>
<p>In contrast with
owned boxes, where the holder of an owned box is the owner of the pointed-to
memory, references never imply ownership - they are "borrowed".
You can borrow a reference to
any object, and the compiler verifies that it cannot outlive the lifetime of
the object.</p>

<p>As an example, consider a simple struct type, <code>Point</code>:</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">Point</span> {
    <span class="ident">x</span>: <span class="ident">f64</span>,
    <span class="ident">y</span>: <span class="ident">f64</span>
}
</pre>

<p>We can use this simple definition to allocate points in many different
ways. For example, in this code, each of these local variables
contains a point, but allocated in a different location:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">on_the_stack</span> :     <span class="ident">Point</span>  <span class="op">=</span>     <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">3.0</span>, <span class="ident">y</span>: <span class="number">4.0</span> };
<span class="kw">let</span> <span class="ident">owned_box</span>    : <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Point</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">7.0</span>, <span class="ident">y</span>: <span class="number">9.0</span> };
</pre>

<p>Suppose we want to write a procedure that computes the distance
between any two points, no matter where they are stored. One option is
to define a function that takes two arguments of type point—that is,
it takes the points by value. But this will cause the points to be
copied when we call the function. For points, this is probably not so
bad, but often copies are expensive. So we’d like to define a function
that takes the points by pointer. We can use references to do this:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">compute_distance</span>(<span class="ident">p1</span>: <span class="kw-2">&amp;</span><span class="ident">Point</span>, <span class="ident">p2</span>: <span class="kw-2">&amp;</span><span class="ident">Point</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {
    <span class="kw">let</span> <span class="ident">x_d</span> <span class="op">=</span> <span class="ident">p1</span>.<span class="ident">x</span> <span class="op">-</span> <span class="ident">p2</span>.<span class="ident">x</span>;
    <span class="kw">let</span> <span class="ident">y_d</span> <span class="op">=</span> <span class="ident">p1</span>.<span class="ident">y</span> <span class="op">-</span> <span class="ident">p2</span>.<span class="ident">y</span>;
    (<span class="ident">x_d</span> <span class="op">*</span> <span class="ident">x_d</span> <span class="op">+</span> <span class="ident">y_d</span> <span class="op">*</span> <span class="ident">y_d</span>).<span class="ident">sqrt</span>()
}
</pre>

<p>Now we can call <code>compute_distance()</code> in various ways:</p>
<pre class="rust "><span class="ident">compute_distance</span>(<span class="kw-2">&amp;</span><span class="ident">on_the_stack</span>, <span class="ident">owned_box</span>);
</pre>

<p>Here the <code>&amp;</code> operator is used to take the address of the variable
<code>on_the_stack</code>; this is because <code>on_the_stack</code> has the type <code>Point</code>
(that is, a struct value) and we have to take its address to get a
reference. We also call this <em>borrowing</em> the local variable
<code>on_the_stack</code>, because we are creating an alias: that is, another
route to the same data.</p>

<p>In the case of <code>owned_box</code>, however, no
explicit action is necessary. The compiler will automatically convert
a box <code>box point</code> to a reference like
<code>&amp;point</code>. This is another form of borrowing; in this case, the
contents of the owned box are being lent out.</p>

<p>Whenever a value is borrowed, there are some limitations on what you
can do with the original. For example, if the contents of a variable
have been lent out, you cannot send that variable to another task, nor
will you be permitted to take actions that might cause the borrowed
value to be freed or to change its type. This rule should make
intuitive sense: you must wait for a borrowed value to be returned
(that is, for the reference to go out of scope) before you can
make full use of it again.</p>

<p>For a more in-depth explanation of references and lifetimes, read the
<a href="http://static.rust-lang.org/doc/master/guide-lifetimes.html">references and lifetimes guide</a>.</p>

<h2 id="freezing" class="section-header"><a href="#freezing">11.1 Freezing(冻结)</a></h2>
<p>Lending an &amp;-pointer to an object freezes it and prevents mutation—even if the object was declared as <code>mut</code>.
<code>Freeze</code> objects have freezing enforced statically at compile-time. An example
of a non-<code>Freeze</code> type is <a href="http://static.rust-lang.org/doc/master/std/cell/struct.RefCell.html"><code>RefCell&lt;T&gt;</code></a>.</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">x</span> <span class="op">=</span> <span class="number">5</span>;
{
    <span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="ident">x</span>;<span class="comment"> // `x` is now frozen. It cannot be modified or re-assigned.
</span>}<span class="comment">
// `x` is now unfrozen again
</span></pre>

<h1 id="dereferencing-pointers" class="section-header"><a href="#dereferencing-pointers">12 Dereferencing pointers(解引用指针)</a></h1>
<p>Rust uses the unary star operator (<code>*</code>) to access the contents of a
box or pointer, similarly to C.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">owned</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">10</span>;
<span class="kw">let</span> <span class="ident">borrowed</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="number">20</span>;

<span class="kw">let</span> <span class="ident">sum</span> <span class="op">=</span> <span class="op">*</span><span class="ident">owned</span> <span class="op">+</span> <span class="op">*</span><span class="ident">borrowed</span>;
</pre>

<p>Dereferenced mutable pointers may appear on the left hand side of
assignments. Such an assignment modifies the value that the pointer
points to.</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">owned</span> <span class="op">=</span> <span class="kw">box</span> <span class="number">10</span>;

<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">value</span> <span class="op">=</span> <span class="number">20</span>;
<span class="kw">let</span> <span class="ident">borrowed</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="ident">value</span>;

<span class="op">*</span><span class="ident">owned</span> <span class="op">=</span> <span class="op">*</span><span class="ident">borrowed</span> <span class="op">+</span> <span class="number">100</span>;
<span class="op">*</span><span class="ident">borrowed</span> <span class="op">=</span> <span class="op">*</span><span class="ident">owned</span> <span class="op">+</span> <span class="number">1000</span>;
</pre>

<p>Pointers have high operator precedence, but lower precedence than the
dot operator used for field and method access. This precedence order
can sometimes make code awkward and parenthesis-filled.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">start</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">10.0</span>, <span class="ident">y</span>: <span class="number">20.0</span> };
<span class="kw">let</span> <span class="ident">end</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">Point</span> { <span class="ident">x</span>: (<span class="op">*</span><span class="ident">start</span>).<span class="ident">x</span> <span class="op">+</span> <span class="number">100.0</span>, <span class="ident">y</span>: (<span class="op">*</span><span class="ident">start</span>).<span class="ident">y</span> <span class="op">+</span> <span class="number">100.0</span> };
<span class="kw">let</span> <span class="ident">rect</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="ident">Rectangle</span>(<span class="op">*</span><span class="ident">start</span>, <span class="op">*</span><span class="ident">end</span>);
<span class="kw">let</span> <span class="ident">area</span> <span class="op">=</span> (<span class="op">*</span><span class="ident">rect</span>).<span class="ident">area</span>();
</pre>

<p>To combat this ugliness the dot operator applies <em>automatic pointer
dereferencing</em> to the receiver (the value on the left-hand side of the
dot), so in most cases, explicitly dereferencing the receiver is not necessary.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">start</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">10.0</span>, <span class="ident">y</span>: <span class="number">20.0</span> };
<span class="kw">let</span> <span class="ident">end</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="ident">start</span>.<span class="ident">x</span> <span class="op">+</span> <span class="number">100.0</span>, <span class="ident">y</span>: <span class="ident">start</span>.<span class="ident">y</span> <span class="op">+</span> <span class="number">100.0</span> };
<span class="kw">let</span> <span class="ident">rect</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="ident">Rectangle</span>(<span class="op">*</span><span class="ident">start</span>, <span class="op">*</span><span class="ident">end</span>);
<span class="kw">let</span> <span class="ident">area</span> <span class="op">=</span> <span class="ident">rect</span>.<span class="ident">area</span>();
</pre>

<p>You can write an expression that dereferences any number of pointers
automatically. For example, if you feel inclined, you could write
something silly like</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">point</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="kw">box</span> <span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">10.0</span>, <span class="ident">y</span>: <span class="number">20.0</span> };
<span class="macro">println</span><span class="macro">!</span>(<span class="string">"{:f}"</span>, <span class="ident">point</span>.<span class="ident">x</span>);
</pre>

<p>The indexing operator (<code>[]</code>) also auto-dereferences.</p>

<h1 id="vectors-and-strings" class="section-header"><a href="#vectors-and-strings">13 Vectors and strings(矢量和字符串)</a></h1>
<p>A vector is a contiguous block of memory containing zero or more values of the
same type. Rust also supports vector reference types, called slices, which are
a view into a block of memory represented as a pointer and a length.</p>

<p>Strings are represented as vectors of <code>u8</code>, with the guarantee of containing a
valid UTF-8 sequence.</p>

<p>Fixed-size vectors are an unboxed block of memory, with the element length as
part of the type. A fixed-size vector owns the elements it contains, so the
elements are mutable if the vector is mutable. Fixed-size strings do not exist.</p>
<pre class="rust "><span class="comment">// A fixed-size vector
</span><span class="kw">let</span> <span class="ident">numbers</span> <span class="op">=</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
<span class="kw">let</span> <span class="ident">more_numbers</span> <span class="op">=</span> <span class="ident">numbers</span>;<span class="comment">

// The type of a fixed-size vector is written as `[Type, ..length]`
</span><span class="kw">let</span> <span class="ident">five_zeroes</span>: [<span class="ident">int</span>, ..<span class="number">5</span>] <span class="op">=</span> [<span class="number">0</span>, ..<span class="number">5</span>];
</pre>

<p>A unique vector is dynamically sized, and has a destructor to clean up
allocated memory on the heap. A unique vector owns the elements it contains, so
the elements are mutable if the vector is mutable.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">strbuf</span>::<span class="ident">StrBuf</span>;<span class="comment">

// A dynamically sized vector (unique vector)
</span><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">numbers</span> <span class="op">=</span> <span class="macro">vec</span><span class="macro">!</span>[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
<span class="ident">numbers</span>.<span class="ident">push</span>(<span class="number">4</span>);
<span class="ident">numbers</span>.<span class="ident">push</span>(<span class="number">5</span>);<span class="comment">

// The type of a unique vector is written as `Vec&lt;int&gt;`
</span><span class="kw">let</span> <span class="ident">more_numbers</span>: <span class="ident">Vec</span><span class="op">&lt;</span><span class="ident">int</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">numbers</span>.<span class="ident">move_iter</span>().<span class="ident">map</span>(<span class="op">|</span><span class="ident">i</span><span class="op">|</span> <span class="ident">i</span><span class="op">+</span><span class="number">1</span>).<span class="ident">collect</span>();<span class="comment">

// The original `numbers` value can no longer be used, due to move semantics.

</span><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">string</span> <span class="op">=</span> <span class="ident">StrBuf</span>::<span class="ident">from_str</span>(<span class="string">"fo"</span>);
<span class="ident">string</span>.<span class="ident">push_char</span>(<span class="string">'o'</span>);
</pre>

<p>Slices are similar to fixed-size vectors, but the length is not part of the
type. They simply point into a block of memory and do not have ownership over
the elements.</p>
<pre class="rust "><span class="comment">// A slice
</span><span class="kw">let</span> <span class="ident">xs</span> <span class="op">=</span> <span class="kw-2">&amp;</span>[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];<span class="comment">

// Slices have their type written as `&amp;[int]`
</span><span class="kw">let</span> <span class="ident">ys</span>: <span class="kw-2">&amp;</span>[<span class="ident">int</span>] <span class="op">=</span> <span class="ident">xs</span>;<span class="comment">

// Other vector types coerce to slices
</span><span class="kw">let</span> <span class="ident">three</span> <span class="op">=</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
<span class="kw">let</span> <span class="ident">zs</span>: <span class="kw-2">&amp;</span>[<span class="ident">int</span>] <span class="op">=</span> <span class="ident">three</span>;<span class="comment">

// An unadorned string literal is an immutable string slice
</span><span class="kw">let</span> <span class="ident">string</span> <span class="op">=</span> <span class="string">"foobar"</span>;<span class="comment">

// A string slice type is written as `&amp;str`
</span><span class="kw">let</span> <span class="ident">view</span>: <span class="kw-2">&amp;</span><span class="ident">str</span> <span class="op">=</span> <span class="ident">string</span>.<span class="ident">slice</span>(<span class="number">0</span>, <span class="number">3</span>);
</pre>

<p>Mutable slices also exist, just as there are mutable references. However, there
are no mutable string slices. Strings are a multi-byte encoding (UTF-8) of
Unicode code points, so they cannot be freely mutated without the ability to
alter the length.</p>
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">xs</span> <span class="op">=</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
<span class="kw">let</span> <span class="ident">view</span> <span class="op">=</span> <span class="ident">xs</span>.<span class="ident">mut_slice</span>(<span class="number">0</span>, <span class="number">2</span>);
<span class="ident">view</span>[<span class="number">0</span>] <span class="op">=</span> <span class="number">5</span>;<span class="comment">

// The type of a mutable slice is written as `&amp;mut [T]`
</span><span class="kw">let</span> <span class="ident">ys</span>: <span class="kw-2">&amp;</span><span class="kw-2">mut</span> [<span class="ident">int</span>] <span class="op">=</span> <span class="kw-2">&amp;</span><span class="kw-2">mut</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
</pre>

<p>Square brackets denote indexing into a slice or fixed-size vector:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">crayons</span>: [<span class="ident">Crayon</span>, ..<span class="number">3</span>] <span class="op">=</span> [<span class="ident">BananaMania</span>, <span class="ident">Beaver</span>, <span class="ident">Bittersweet</span>];
<span class="kw">match</span> <span class="ident">crayons</span>[<span class="number">0</span>] {
    <span class="ident">Bittersweet</span> <span class="op">=&gt;</span> <span class="ident">draw_scene</span>(<span class="ident">crayons</span>[<span class="number">0</span>]),
    _ <span class="op">=&gt;</span> ()
}
</pre>

<p>A slice or fixed-size vector can be destructured using pattern matching:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">numbers</span>: <span class="kw-2">&amp;</span>[<span class="ident">int</span>] <span class="op">=</span> <span class="kw-2">&amp;</span>[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];
<span class="kw">let</span> <span class="ident">score</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">numbers</span> {
    [] <span class="op">=&gt;</span> <span class="number">0</span>,
    [<span class="ident">a</span>] <span class="op">=&gt;</span> <span class="ident">a</span> <span class="op">*</span> <span class="number">10</span>,
    [<span class="ident">a</span>, <span class="ident">b</span>] <span class="op">=&gt;</span> <span class="ident">a</span> <span class="op">*</span> <span class="number">6</span> <span class="op">+</span> <span class="ident">b</span> <span class="op">*</span> <span class="number">4</span>,
    [<span class="ident">a</span>, <span class="ident">b</span>, <span class="ident">c</span>, ..<span class="ident">rest</span>] <span class="op">=&gt;</span> <span class="ident">a</span> <span class="op">*</span> <span class="number">5</span> <span class="op">+</span> <span class="ident">b</span> <span class="op">*</span> <span class="number">3</span> <span class="op">+</span> <span class="ident">c</span> <span class="op">*</span> <span class="number">2</span> <span class="op">+</span> <span class="ident">rest</span>.<span class="ident">len</span>() <span class="kw">as</span> <span class="ident">int</span>
};
</pre>

<p>Both vectors and strings support a number of useful <a href="#methods">methods</a>,
defined in <a href="http://static.rust-lang.org/doc/master/std/vec/index.html"><code>std::vec</code></a>, <a href="http://static.rust-lang.org/doc/master/std/slice/index.html"><code>std::slice</code></a>, and <a href="http://static.rust-lang.org/doc/master/std/str/index.html"><code>std::str</code></a>.</p>

<h1 id="ownership-escape-hatches" class="section-header"><a href="#ownership-escape-hatches">14 Ownership escape hatches(所有权脱离通道)</a></h1>
<p>Ownership can cleanly describe tree-like data structures, and 
references provide non-owning pointers. However, more flexibility is 
often desired and Rust provides ways to escape from strict
single parent ownership.</p>

<p>The standard library provides the <code>std::rc::Rc</code> pointer type to express <em>shared ownership</em> over a
reference counted box. As soon as all of the <code>Rc</code> pointers go out of scope, the box and the
contained value are destroyed.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">rc</span>::<span class="ident">Rc</span>;<span class="comment">

// A fixed-size array allocated in a reference-counted box
</span><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="ident">Rc</span>::<span class="ident">new</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>]);
<span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="ident">x</span>.<span class="ident">clone</span>();<span class="comment"> // a new owner
</span><span class="kw">let</span> <span class="ident">z</span> <span class="op">=</span> <span class="ident">x</span>;<span class="comment"> // this moves `x` into `z`, rather than creating a new owner

</span><span class="macro">assert</span><span class="macro">!</span>(<span class="op">*</span><span class="ident">z</span> <span class="op">==</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>]);<span class="comment">

// the variable is mutable, but not the contents of the box
</span><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">a</span> <span class="op">=</span> <span class="ident">Rc</span>::<span class="ident">new</span>([<span class="number">10</span>, <span class="number">9</span>, <span class="number">8</span>, <span class="number">7</span>, <span class="number">6</span>, <span class="number">5</span>, <span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>]);
<span class="ident">a</span> <span class="op">=</span> <span class="ident">z</span>;
</pre>

<p>A garbage collected pointer is provided via <code>std::gc::Gc</code>, with a task-local garbage collector
having ownership of the box. It allows the creation of cycles, and the individual <code>Gc</code> pointers do
not have a destructor.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">gc</span>::<span class="ident">Gc</span>;<span class="comment">

// A fixed-size array allocated in a garbage-collected box
</span><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="ident">Gc</span>::<span class="ident">new</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>]);
<span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="ident">x</span>;<span class="comment"> // does not perform a move, unlike with `Rc`
</span><span class="kw">let</span> <span class="ident">z</span> <span class="op">=</span> <span class="ident">x</span>;

<span class="macro">assert</span><span class="macro">!</span>(<span class="op">*</span><span class="ident">z</span>.<span class="ident">borrow</span>() <span class="op">==</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>]);
</pre>

<p>With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
it's possible to use <em>dynamic</em> mutability via types like <code>std::cell::Cell</code> where freezing is handled
via dynamic checks and can fail at runtime.</p>

<p>The <code>Rc</code> and <code>Gc</code> types are not sendable, so they cannot be used to share memory between tasks. Safe
immutable and mutable shared memory is provided by the <code>extra::arc</code> module.</p>

<h1 id="closures" class="section-header"><a href="#closures">15 Closures(闭包)</a></h1>
<p>Named functions, like those we've seen so far, may not refer to local
variables declared outside the function: they do not close over their
environment (sometimes referred to as "capturing" variables in their
environment). For example, you couldn't write the following:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="number">3</span>;<span class="comment">

// `fun` cannot refer to `x`
</span><span class="kw">fn</span> <span class="ident">fun</span>() <span class="op">-&gt;</span> () { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>); }
</pre>

<p>A <em>closure</em> does support accessing the enclosing scope; below we will create
2 <em>closures</em> (nameless functions). Compare how <code>||</code> replaces <code>()</code> and how
they try to access <code>x</code>:</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">x</span> <span class="op">=</span> <span class="number">3</span>;<span class="comment">

// `fun` is an invalid definition
</span><span class="kw">fn</span>  <span class="ident">fun</span>       () <span class="op">-&gt;</span> () { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>) }<span class="comment">  // cannot capture from enclosing scope
</span><span class="kw">let</span> <span class="ident">closure</span> <span class="op">=</span> <span class="op">||</span> <span class="op">-&gt;</span> () { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>) };<span class="comment"> // can capture from enclosing scope

// `fun_arg` is an invalid definition
</span><span class="kw">fn</span>  <span class="ident">fun_arg</span>       (<span class="ident">arg</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> () { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">arg</span> <span class="op">+</span> <span class="ident">x</span>) }<span class="comment">  // cannot capture
</span><span class="kw">let</span> <span class="ident">closure_arg</span> <span class="op">=</span> <span class="op">|</span><span class="ident">arg</span>: <span class="ident">int</span><span class="op">|</span> <span class="op">-&gt;</span> () { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">arg</span> <span class="op">+</span> <span class="ident">x</span>) };<span class="comment"> // can capture
//                      ^
// Requires a type because the implementation needs to know which `+` to use.
// In the future, the implementation may not need the help.

</span><span class="ident">fun</span>();<span class="comment">          // Still won't work
</span><span class="ident">closure</span>();<span class="comment">      // Prints: 3

</span><span class="ident">fun_arg</span>(<span class="number">7</span>);<span class="comment">     // Still won't work
</span><span class="ident">closure_arg</span>(<span class="number">7</span>);<span class="comment"> // Prints: 10
</span></pre>

<p>Closures begin with the argument list between vertical bars and are followed by
a single expression. Remember that a block, <code>{ &lt;expr1&gt;; &lt;expr2&gt;; ... }</code>, is
considered a single expression: it evaluates to the result of the last
expression it contains if that expression is not followed by a semicolon,
otherwise the block evaluates to <code>()</code>, the unit value.</p>
闭包开始是在竖线之间的参数列表然后随着一个单一表达式.记住块{}被认为是单一的表达式:如果最后一个表达式没有跟着一个分号.
那么这个块将评估结果，否则块估值为()-单元值.
<p>In general, return types and all argument types must be specified
explicitly for function definitions.  (As previously mentioned in the
<a href="#functions">Functions section</a>, omitting the return type from a
function declaration is synonymous with an explicit declaration of
return type unit, <code>()</code>.)</p>
一般,返回类型和所有实际参数类型必须在函数定义的时候显示定义.(入前提示<a href="#functions">Functions section</a>,
函数定义的时候省略返回类型也就是等同于显示声明返回类型位unit ().
<pre class="rust "><span class="kw">fn</span>  <span class="ident">fun</span>   (<span class="ident">x</span>: <span class="ident">int</span>)         { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>) }<span class="comment"> // this is same as saying `-&gt; ()`
</span><span class="kw">fn</span>  <span class="ident">square</span>(<span class="ident">x</span>: <span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">uint</span> { (<span class="ident">x</span> <span class="op">*</span> <span class="ident">x</span>) <span class="kw">as</span> <span class="ident">uint</span> }<span class="comment">   // other return types are explicit

// Error: mismatched types: expected `()` but found `uint`
</span><span class="kw">fn</span>  <span class="ident">badfun</span>(<span class="ident">x</span>: <span class="ident">int</span>)         { (<span class="ident">x</span> <span class="op">*</span> <span class="ident">x</span>) <span class="kw">as</span> <span class="ident">uint</span> }
</pre>

<p>On the other hand, the compiler can usually infer both the argument
and return types for a closure expression; therefore they are often
omitted, since both a human reader and the compiler can deduce the
types from the immediate context.  This is in contrast to function
declarations, which require types to be specified and are not subject
to type inference. Compare:</p>
另一方面,编译器通常可以推断闭包表达式的实际参数和返回类型.所以它们经常省略,人类读者和编译都可以直接根据上下文推断类型。
这相对于函数声明要求需要指定类型以及不允许类型推断.比较:
<pre class="rust "><span class="comment">// `fun` as a function declaration cannot infer the type of `x`, so it must be provided
</span><span class="kw">fn</span>  <span class="ident">fun</span>       (<span class="ident">x</span>: <span class="ident">int</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>) }
<span class="kw">let</span> <span class="ident">closure</span> <span class="op">=</span> <span class="op">|</span><span class="ident">x</span>     <span class="op">|</span> { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>) };<span class="comment"> // infers `x: int`, return type `()`

// For closures, omitting a return type is *not* synonymous with `-&gt; ()`
</span><span class="kw">let</span> <span class="ident">add_3</span>   <span class="op">=</span> <span class="op">|</span><span class="ident">y</span>     <span class="op">|</span> { <span class="number">3i</span> <span class="op">+</span> <span class="ident">y</span> };<span class="comment"> // infers `y: int`, return type `int`.

</span><span class="ident">fun</span>(<span class="number">10</span>);<span class="comment">            // Prints 10
</span><span class="ident">closure</span>(<span class="number">20</span>);<span class="comment">        // Prints 20
</span><span class="ident">closure</span>(<span class="ident">add_3</span>(<span class="number">30</span>));<span class="comment"> // Prints 33

</span><span class="ident">fun</span>(<span class="string">"String"</span>);<span class="comment"> // Error: mismatched types

// Error: mismatched types
// inference already assigned `closure` the type `|int| -&gt; ()`
</span><span class="ident">closure</span>(<span class="string">"String"</span>);
</pre>

<p>In cases where the compiler needs assistance, the arguments and return
types may be annotated on closures, using the same notation as shown
earlier.  In the example below, since different types provide an
implementation for the operator <code>*</code>, the argument type for the <code>x</code>
parameter must be explicitly provided.</p>
<pre class="rust "><span class="comment">// Error: the type of `x` must be known to be used with `x * x`
</span><span class="kw">let</span> <span class="ident">square</span> <span class="op">=</span> <span class="op">|</span><span class="ident">x</span>     <span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">uint</span> { (<span class="ident">x</span> <span class="op">*</span> <span class="ident">x</span>) <span class="kw">as</span> <span class="ident">uint</span> };
</pre>

<p>In the corrected version, the argument type is explicitly annotated,
while the return type can still be inferred.</p>
<pre class="rust "><span class="kw">let</span> <span class="ident">square_explicit</span> <span class="op">=</span> <span class="op">|</span><span class="ident">x</span>: <span class="ident">int</span><span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">uint</span> { (<span class="ident">x</span> <span class="op">*</span> <span class="ident">x</span>) <span class="kw">as</span> <span class="ident">uint</span> };
<span class="kw">let</span> <span class="ident">square_infer</span>    <span class="op">=</span> <span class="op">|</span><span class="ident">x</span>: <span class="ident">int</span><span class="op">|</span>         { (<span class="ident">x</span> <span class="op">*</span> <span class="ident">x</span>) <span class="kw">as</span> <span class="ident">uint</span> };

<span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">square_explicit</span>(<span class="number">20</span>));<span class="comment">  // 400
</span><span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">square_infer</span>(<span class="op">-</span><span class="number">20</span>));<span class="comment">    // 400
</span></pre>

<p>There are several forms of closure, each with its own role. The most
common, called a <em>stack closure</em>, has type <code>||</code> and can directly
access local variables in the enclosing scope.</p>
有数种形式的闭包,每一个有它自己的角色.最常用的，称作堆栈闭包:类型列表为||可以在封闭范围内直接访问局部变量.
<pre class="rust "><span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">max</span> <span class="op">=</span> <span class="number">0</span>;
<span class="kw">let</span> <span class="ident">f</span> <span class="op">=</span> <span class="op">|</span><span class="ident">x</span>: <span class="ident">int</span><span class="op">|</span> <span class="kw">if</span> <span class="ident">x</span> <span class="op">&gt;</span> <span class="ident">max</span> { <span class="ident">max</span> <span class="op">=</span> <span class="ident">x</span> };
<span class="kw">for</span> <span class="ident">x</span> <span class="kw">in</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>].<span class="ident">iter</span>() {
    <span class="ident">f</span>(<span class="op">*</span><span class="ident">x</span>);
}
</pre>

<p>Stack closures are very efficient because their environment is
allocated on the call stack and refers by pointer to captured
locals. To ensure that stack closures never outlive the local
variables to which they refer, stack closures are not
first-class. That is, they can only be used in argument position; they
cannot be stored in data structures or returned from
functions. Despite these limitations, stack closures are used
pervasively in Rust code.</p>
堆栈闭包非常有效率因为它们的环境在调用堆栈内被分配可以通过指针引用在局部使用.
确认堆栈闭包永远不会比它们引用的局部变量长命,堆栈闭包不是first-class.也就是它们只能用于实际参数位置.
它们不能被保存在数据结构里或者从函数返回.尽管有如此限制,堆栈闭包在Rust代码里还是普遍被使用.
<h2 id="owned-closures" class="section-header"><a href="#owned-closures">15.1 Owned closures(自有闭包)</a></h2>
<p>Owned closures, written <code>proc</code>,
hold on to things that can safely be sent between
processes. They copy the values they close over,
but they also own them: that is, no other code can access
them. Owned closures are used in concurrent code, particularly
for spawning <a href="http://static.rust-lang.org/doc/master/guide-tasks.html">tasks</a>.</p>
自有闭包,写作proc(进程),控制东西可以安全的在过程之间发送.闭包复制它们最接近的值,同时对这些值也有拥有权们:没有其他代码可以访问它们.
自有闭包常用与并发代码，尤其是spawning 任务.
<p>Closures can be used to spawn tasks.
A practical example of this pattern is found when using the <code>spawn</code> function,
which starts a new task.</p>
闭包常用于spawn任务.
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">task</span>::<span class="ident">spawn</span>;<span class="comment">

// proc is the closure which will be spawned.
</span><span class="ident">spawn</span>(<span class="kw">proc</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"I'm a new task"</span>)
});
</pre>

<h2 id="closure-compatibility" class="section-header"><a href="#closure-compatibility">15.2 Closure compatibility(闭包兼容性)</a></h2>
<p>Rust closures have a convenient subtyping property: you can pass any kind of
closure (as long as the arguments and return types match) to functions
that expect a <code>||</code>. Thus, when writing a higher-order function that
only calls its function argument, and does nothing else with it, you
should almost always declare the type of that argument as <code>||</code>. That way,
callers may pass any kind of closure.</p>
Rust 闭包有一个方便子类型属性:你可以传递任何类型的闭包(只要实际参数和返回类型匹配)给一个函数参数类型为||.
然而,当书写高阶函数只调用它的函数实际参数,并不做其他任何事情,那就就可以声明实际参数类型为||.这个方法,
调用者可以传递任何类型闭包。

<pre class="rust "><span class="kw">fn</span> <span class="ident">call_twice</span>(<span class="ident">f</span>: <span class="op">||</span>) { <span class="ident">f</span>(); <span class="ident">f</span>(); }
<span class="kw">let</span> <span class="ident">closure</span> <span class="op">=</span> <span class="op">||</span> { <span class="string">"I'm a closure, and it doesn't matter what type I am"</span>; };
<span class="kw">fn</span> <span class="ident">function</span>() { <span class="string">"I'm a normal function"</span>; }
<span class="ident">call_twice</span>(<span class="ident">closure</span>);
<span class="ident">call_twice</span>(<span class="ident">function</span>);
</pre>

<blockquote>
<p><em>Note:</em> Both the syntax and the semantics will be changing
in small ways. At the moment they can be unsound in some
scenarios, particularly with non-copyable types.</p>
</blockquote>

<h1 id="methods" class="section-header"><a href="#methods">16 Methods(方法)</a></h1>
<p>Methods are like functions except that they always begin with a special argument,
called <code>self</code>,
which has the type of the method's receiver. The
<code>self</code> argument is like <code>this</code> in C++ and many other languages.
Methods are called with dot notation, as in <code>my_vec.len()</code>.</p>
方法和函数一样除了它们第一个参数总是特殊的实际参数:self.self的类型和方法接受者一致.
self 实参和C++及其他语言中的this相似.方法的调用是通过点语法比如:my_vec.len()
<p><em>Implementations</em>, written with the <code>impl</code> keyword, can define
methods on most Rust types, including structs and enums.
As an example, let's define a <code>draw</code> method on our <code>Shape</code> enum.</p>
实现,简写为impl关键词,可以在Rust大多数类型上定义方法，包括结构和美剧
<pre class="rust "><span class="kw">struct</span> <span class="ident">Point</span> {
    <span class="ident">x</span>: <span class="ident">f64</span>,
    <span class="ident">y</span>: <span class="ident">f64</span>
}

<span class="kw">enum</span> <span class="ident">Shape</span> {
    <span class="ident">Circle</span>(<span class="ident">Point</span>, <span class="ident">f64</span>),
    <span class="ident">Rectangle</span>(<span class="ident">Point</span>, <span class="ident">Point</span>)
}

<span class="kw">impl</span> <span class="ident">Shape</span> {
    <span class="kw">fn</span> <span class="ident">draw</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) {
        <span class="kw">match</span> <span class="op">*</span><span class="self">self</span> {
            <span class="ident">Circle</span>(<span class="ident">p</span>, <span class="ident">f</span>) <span class="op">=&gt;</span> <span class="ident">draw_circle</span>(<span class="ident">p</span>, <span class="ident">f</span>),
            <span class="ident">Rectangle</span>(<span class="ident">p1</span>, <span class="ident">p2</span>) <span class="op">=&gt;</span> <span class="ident">draw_rectangle</span>(<span class="ident">p1</span>, <span class="ident">p2</span>)
        }
    }
}

<span class="kw">let</span> <span class="ident">s</span> <span class="op">=</span> <span class="ident">Circle</span>(<span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">1.0</span>, <span class="ident">y</span>: <span class="number">2.0</span> }, <span class="number">3.0</span>);
<span class="ident">s</span>.<span class="ident">draw</span>();
</pre>

<p>This defines an <em>implementation</em> for <code>Shape</code> containing a single
method, <code>draw</code>. In most respects the <code>draw</code> method is defined
like any other function, except for the name <code>self</code>.</p>

<p>The type of <code>self</code> is the type on which the method is implemented,
or a pointer thereof. As an argument it is written either <code>self</code>,
<code>&amp;self</code>, or <code>~self</code>.
A caller must in turn have a compatible pointer type to call the method.</p>
self类型是实现了该方法的类型,或者这类的一个指针.作为实参写作self,&self,~self之一，相应的
调用也必须兼容方法的指针类型。

<pre class="rust "><span class="kw">impl</span> <span class="ident">Shape</span> {
    <span class="kw">fn</span> <span class="ident">draw_reference</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) {<span class="comment"> /* ... */ </span>}
    <span class="kw">fn</span> <span class="ident">draw_owned</span>(<span class="kw-2">~</span><span class="self">self</span>) {<span class="comment"> /* ... */ </span>}
    <span class="kw">fn</span> <span class="ident">draw_value</span>(<span class="self">self</span>) {<span class="comment"> /* ... */ </span>}
}

<span class="kw">let</span> <span class="ident">s</span> <span class="op">=</span> <span class="ident">Circle</span>(<span class="ident">Point</span> { <span class="ident">x</span>: <span class="number">1.0</span>, <span class="ident">y</span>: <span class="number">2.0</span> }, <span class="number">3.0</span>);

(<span class="kw-2">&amp;</span><span class="ident">s</span>).<span class="ident">draw_reference</span>();
(<span class="kw">box</span> <span class="ident">s</span>).<span class="ident">draw_owned</span>();
<span class="ident">s</span>.<span class="ident">draw_value</span>();
</pre>

<p>Methods typically take a reference self type,
so the compiler will go to great lengths to convert a callee
to a reference.</p>
方法通常采取self引用类型，因此编译器将竭尽全力为被叫转换为引用 

<pre class="rust "><span class="comment">// As with typical function arguments, owned pointers
// are automatically converted to references

</span>(<span class="kw">box</span> <span class="ident">s</span>).<span class="ident">draw_reference</span>();<span class="comment">

// Unlike typical function arguments, the self value will
// automatically be referenced ...
</span><span class="ident">s</span>.<span class="ident">draw_reference</span>();<span class="comment">

// ... and dereferenced
</span>(<span class="op">&amp;</span> <span class="kw-2">&amp;</span><span class="ident">s</span>).<span class="ident">draw_reference</span>();<span class="comment">

// ... and dereferenced and borrowed 借来
</span>(<span class="kw-2">&amp;</span><span class="kw">box</span> <span class="ident">s</span>).<span class="ident">draw_reference</span>();
</pre>

<p>Implementations may also define standalone (sometimes called "static")
methods. The absence of a <code>self</code> parameter distinguishes such methods.
These methods are the preferred way to define constructor functions.</p>
实现也可以定义独立(有时叫做'静态')方法.缺少self参数可以用来区分这种方法.
这些方法是定义构造函数首选的方式.
<pre class="rust "><span class="kw">impl</span> <span class="ident">Circle</span> {
    <span class="kw">fn</span> <span class="ident">area</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {<span class="comment"> /* ... */ </span>}
    <span class="kw">fn</span> <span class="ident">new</span>(<span class="ident">area</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">Circle</span> {<span class="comment"> /* ... */ </span>}
}
</pre>

<p>To call such a method, just prefix it with the type name and a double colon:</p>
调用这种方法,只需要前缀类型名和双冒号:
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span>;
<span class="kw">struct</span> <span class="ident">Circle</span> { <span class="ident">radius</span>: <span class="ident">f64</span> }
<span class="kw">impl</span> <span class="ident">Circle</span> {
    <span class="kw">fn</span> <span class="ident">new</span>(<span class="ident">area</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">Circle</span> { <span class="ident">Circle</span> { <span class="ident">radius</span>: (<span class="ident">area</span> <span class="op">/</span> <span class="ident">PI</span>).<span class="ident">sqrt</span>() } }
}
<span class="kw">let</span> <span class="ident">c</span> <span class="op">=</span> <span class="ident">Circle</span>::<span class="ident">new</span>(<span class="number">42.5</span>);
</pre>

<h1 id="generics" class="section-header"><a href="#generics">17 Generics(泛型)</a></h1>
<p>Throughout this tutorial, we've been defining functions that act only
on specific data types. With type parameters we can also define
functions whose arguments have generic types, and which can be invoked
with a variety of types. Consider a generic <code>map</code> function, which
takes a function <code>function</code> and a vector <code>vector</code> and returns a new
vector consisting of the result of applying <code>function</code> to each element
of <code>vector</code>:</p>
	通过这个训练,我们已经定义了对特定数据类型使用的函数.通过类型参数我们也可以定义函数它的参数是泛型,
	即函数可以通过可变的类型来调用.想想泛型map函数,使用函数和vector参数，然后返回一个新的vector内容是在每个元素
	上都是用函数的结果.
<pre class="rust "><span class="kw">fn</span> <span class="ident">map</span><span class="op">&lt;</span><span class="ident">T</span>, <span class="ident">U</span><span class="op">&gt;</span>(<span class="ident">vector</span>: <span class="kw-2">&amp;</span>[<span class="ident">T</span>], <span class="ident">function</span>: <span class="op">|</span><span class="ident">v</span>: <span class="kw-2">&amp;</span><span class="ident">T</span><span class="op">|</span> <span class="op">-&gt;</span> <span class="ident">U</span>) <span class="op">-&gt;</span> <span class="ident">Vec</span><span class="op">&lt;</span><span class="ident">U</span><span class="op">&gt;</span> {
    <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">accumulator</span> <span class="op">=</span> <span class="ident">Vec</span>::<span class="ident">new</span>();
    <span class="kw">for</span> <span class="ident">element</span> <span class="kw">in</span> <span class="ident">vector</span>.<span class="ident">iter</span>() {
        <span class="ident">accumulator</span>.<span class="ident">push</span>(<span class="ident">function</span>(<span class="ident">element</span>));
    }
    <span class="kw">return</span> <span class="ident">accumulator</span>;
}
</pre>

<p>When defined with type parameters, as denoted by <code>&lt;T, U&gt;</code>, this
function can be applied to any type of vector, as long as the type of
<code>function</code>'s argument and the type of the vector's contents agree with
each other.</p>

<p>Inside a generic function, the names of the type parameters
(capitalized by convention) stand for opaque types. All you can do
with instances of these types is pass them around: you can't apply any
operations to them or pattern-match on them. Note that instances of
generic types are often passed by pointer. For example, the parameter
<code>function()</code> is supplied with a pointer to a value of type <code>T</code> and not
a value of type <code>T</code> itself. This ensures that the function works with
the broadest set of types possible, since some types are expensive or
illegal to copy and pass by value.</p>

<p>Generic <code>type</code>, <code>struct</code>, and <code>enum</code> declarations follow the same pattern:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">collections</span>;
<span class="kw">type</span> <span class="ident">Set</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> <span class="op">=</span> <span class="ident">collections</span>::<span class="ident">HashMap</span><span class="op">&lt;</span><span class="ident">T</span>, ()<span class="op">&gt;</span>;

<span class="kw">struct</span> <span class="ident">Stack</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="ident">elements</span>: <span class="kw-2">~</span>[<span class="ident">T</span>]
}

<span class="kw">enum</span> <span class="prelude-ty">Option</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="prelude-val">Some</span>(<span class="ident">T</span>),
    <span class="prelude-val">None</span>
}
</pre>

<p>These declarations can be instantiated to valid types like <code>Set&lt;int&gt;</code>,
<code>Stack&lt;int&gt;</code>, and <code>Option&lt;int&gt;</code>.</p>

<p>The last type in that example, <code>Option</code>, appears frequently in Rust code.
Because Rust does not have null pointers (except in unsafe code), we need
another way to write a function whose result isn't defined on every possible
combination of arguments of the appropriate types. The usual way is to write
a function that returns <code>Option&lt;T&gt;</code> instead of <code>T</code>.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">radius</span>(<span class="ident">shape</span>: <span class="ident">Shape</span>) <span class="op">-&gt;</span> <span class="prelude-ty">Option</span><span class="op">&lt;</span><span class="ident">f64</span><span class="op">&gt;</span> {
    <span class="kw">match</span> <span class="ident">shape</span> {
        <span class="ident">Circle</span>(_, <span class="ident">radius</span>) <span class="op">=&gt;</span> <span class="prelude-val">Some</span>(<span class="ident">radius</span>),
        <span class="ident">Rectangle</span>(..)     <span class="op">=&gt;</span> <span class="prelude-val">None</span>
    }
}
</pre>

<p>The Rust compiler compiles generic functions very efficiently by
<em>monomorphizing</em> them. <em>Monomorphization</em> is a fancy name for a simple
idea: generate a separate copy of each generic function at each call site,
a copy that is specialized to the argument
types and can thus be optimized specifically for them. In this
respect, Rust's generics have similar performance characteristics to
C++ templates.</p>
Rust编译器编译泛型函数时通过单态化技术提高效率.单态是一个简单想法的奇特名字:
在泛型函数每次调用的时候产生一个独立的副本.副本是特化实际参数类型和特别的优化.
从这个角度来说,Rust的泛型和C++的模板具有相同的性能特点.
<h2 id="traits" class="section-header"><a href="#traits">17.1 Traits(特性)</a></h2>
<p>Within a generic function—that is, a function parameterized by a
type parameter, say, <code>T</code>—the operations we can do on arguments of
type <code>T</code> are quite limited.  After all, since we don't know what type
<code>T</code> will be instantiated with, we can't safely modify or query values
of type <code>T</code>.  This is where <em>traits</em> come into play. Traits are Rust's
most powerful tool for writing polymorphic code. Java developers will
see them as similar to Java interfaces, and Haskellers will notice
their similarities to type classes. Rust's traits give us a way to
express <em>bounded polymorphism</em>: by limiting the set of possible types
that a type parameter could refer to, they expand the number of
operations we can safely perform on arguments of that type.</p>

<p>As motivation, let us consider copying of values in Rust.  The <code>clone</code>
method is not defined for values of every type.  One reason is
user-defined destructors: copying a value of a type that has a
destructor could result in the destructor running multiple times.
Therefore, values of types that have destructors cannot be copied
unless we explicitly implement <code>clone</code> for them.</p>

<p>This complicates handling of generic functions.
If we have a function with a type parameter <code>T</code>,
can we copy values of type <code>T</code> inside that function?
In Rust, we can't,
and if we try to run the following code the compiler will complain.</p>
<pre class="rust "><span class="comment">// This does not compile
</span><span class="kw">fn</span> <span class="ident">head_bad</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>(<span class="ident">v</span>: <span class="kw-2">&amp;</span>[<span class="ident">T</span>]) <span class="op">-&gt;</span> <span class="ident">T</span> {
    <span class="ident">v</span>[<span class="number">0</span>]<span class="comment"> // error: copying a non-copyable value
</span>}
</pre>

<p>However, we can tell the compiler
that the <code>head</code> function is only for copyable types.
In Rust, copyable types are those that <em>implement the <code>Clone</code> trait</em>.
We can then explicitly create a second copy of the value we are returning
by calling the <code>clone</code> method:</p>
<pre class="rust "><span class="comment">// This does
</span><span class="kw">fn</span> <span class="ident">head</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Clone</span><span class="op">&gt;</span>(<span class="ident">v</span>: <span class="kw-2">&amp;</span>[<span class="ident">T</span>]) <span class="op">-&gt;</span> <span class="ident">T</span> {
    <span class="ident">v</span>[<span class="number">0</span>].<span class="ident">clone</span>()
}
</pre>

<p>The bounded type parameter <code>T: Clone</code> says that <code>head</code>
can be called on an argument of type <code>&amp;[T]</code> for any <code>T</code>,
so long as there is an implementation of the
<code>Clone</code> trait for <code>T</code>.
When instantiating a generic function,
we can only instantiate it with types
that implement the correct trait,
so we could not apply <code>head</code> to a vector whose elements are of some type
that does not implement <code>Clone</code>.</p>

<p>While most traits can be defined and implemented by user code,
three traits are automatically derived and implemented
for all applicable types by the compiler,
and may not be overridden:</p>

<ul>
<li><p><code>Send</code> - Sendable types.
Types are sendable
unless they contain references.</p></li>
<li><p><code>Share</code> - Types that are <em>threadsafe</em>
These are types that are safe to be used across several threads with access to
a <code>&amp;T</code> pointer. <code>Mutex&lt;T&gt;</code> is an example of a <em>sharable</em> type with internal mutable data.</p></li>
<li><p><code>'static</code> - Non-borrowed types.
These are types that do not contain any data whose lifetime is bound to
a particular stack frame. These are types that do not contain any
references, or types where the only contained references
have the <code>'static</code> lifetime. (For more on named lifetimes and their uses,
see the <a href="http://static.rust-lang.org/doc/master/guide-lifetimes.html">references and lifetimes guide</a>.)</p></li>
</ul>

<blockquote>
<p><em>Note:</em> These built-in traits were referred to as 'kinds' in earlier
iterations of the language, and often still are.</p>
</blockquote>

<p>Additionally, the <code>Drop</code> trait is used to define destructors. This
trait provides one method called <code>drop</code>, which is automatically
called when a value of the type that implements this trait is
destroyed, either because the value went out of scope or because the
garbage collector reclaimed it.</p>
<pre class="rust "><span class="kw">struct</span> <span class="ident">TimeBomb</span> {
    <span class="ident">explosivity</span>: <span class="ident">uint</span>
}

<span class="kw">impl</span> <span class="ident">Drop</span> <span class="kw">for</span> <span class="ident">TimeBomb</span> {
    <span class="kw">fn</span> <span class="ident">drop</span>(<span class="kw-2">&amp;</span><span class="kw-2">mut</span> <span class="self">self</span>) {
        <span class="kw">for</span> _ <span class="kw">in</span> <span class="ident">range</span>(<span class="number">0</span>, <span class="self">self</span>.<span class="ident">explosivity</span>) {
            <span class="macro">println</span><span class="macro">!</span>(<span class="string">"blam!"</span>);
        }
    }
}
</pre>

<p>It is illegal to call <code>drop</code> directly. Only code inserted by the compiler
may call it.</p>

<h2 id="declaring-and-implementing-traits" class="section-header"><a href="#declaring-and-implementing-traits">17.2 Declaring and implementing traits(声明和实现特性)</a></h2>
<p>At its simplest, a trait is a set of zero or more <em>method signatures</em>.
For example, we could declare the trait
<code>Printable</code> for things that can be printed to the console,
with a single method signature:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Printable</span> {
    <span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>);
}
</pre>

<p>We say that the <code>Printable</code> trait <em>provides</em> a <code>print</code> method with the
given signature.  This means that we can call <code>print</code> on an argument
of any type that implements the <code>Printable</code> trait.</p>

<p>Rust's built-in <code>Send</code> and <code>Share</code> types are examples of traits that
don't provide any methods.</p>

<p>Traits may be implemented for specific types with <a href="#methods">impls</a>. An impl for
a particular trait gives an implementation of the methods that
trait provides.  For instance, the following impls of
<code>Printable</code> for <code>int</code> and <code>StrBuf</code> give implementations of the <code>print</code>
method.</p>
<pre class="rust "><span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">int</span> {
    <span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{:?}"</span>, <span class="op">*</span><span class="self">self</span>) }
}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">StrBuf</span> {
    <span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="op">*</span><span class="self">self</span>) }
}
</pre>

<p>Methods defined in an impl for a trait may be called just like
any other method, using dot notation, as in <code>1.print()</code>.</p>

<h2 id="default-method-implementations-in-trait-definitions" class="section-header"><a href="#default-method-implementations-in-trait-definitions">17.3 Default method implementations in trait definitions(特性定义中默认方法实现)</a></h2>
<p>Sometimes, a method that a trait provides will have the same
implementation for most or all of the types that implement that trait.
For instance, suppose that we wanted <code>bool</code>s and <code>f32</code>s to be
printable, and that we wanted the implementation of <code>print</code> for those
types to be exactly as it is for <code>int</code>, above:</p>
<pre class="rust "><span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">f32</span> {
    <span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{:?}"</span>, <span class="op">*</span><span class="self">self</span>) }
}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">bool</span> {
    <span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{:?}"</span>, <span class="op">*</span><span class="self">self</span>) }
}
</pre>

<p>This works fine, but we've now repeated the same definition of <code>print</code>
in three places.  Instead of doing that, we can simply include the
definition of <code>print</code> right in the trait definition, instead of just
giving its signature.  That is, we can write the following:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Printable</span> {<span class="comment">
    // Default method implementation
    </span><span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{:?}"</span>, <span class="op">*</span><span class="self">self</span>) }
}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">int</span> {}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">StrBuf</span> {
    <span class="kw">fn</span> <span class="ident">print</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="op">*</span><span class="self">self</span>) }
}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">bool</span> {}

<span class="kw">impl</span> <span class="ident">Printable</span> <span class="kw">for</span> <span class="ident">f32</span> {}
</pre>

<p>Here, the impls of <code>Printable</code> for <code>int</code>, <code>bool</code>, and <code>f32</code> don't
need to provide an implementation of <code>print</code>, because in the absence
of a specific implementation, Rust just uses the <em>default method</em>
provided in the trait definition.  Depending on the trait, default
methods can save a great deal of boilerplate code from having to be
written in impls.  Of course, individual impls can still override the
default method for <code>print</code>, as is being done above in the impl for
<code>StrBuf</code>.</p>

<h2 id="type-parameterized-traits" class="section-header"><a href="#type-parameterized-traits">17.4 Type-parameterized traits(类型参数化的特性)</a></h2>
<p>Traits may be parameterized by type variables.  For example, a trait
for generalized sequence types might look like the following:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Seq</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {
    <span class="kw">fn</span> <span class="ident">length</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">uint</span>;
}

<span class="kw">impl</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> <span class="ident">Seq</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> <span class="kw">for</span> <span class="kw-2">~</span>[<span class="ident">T</span>] {
    <span class="kw">fn</span> <span class="ident">length</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">uint</span> { <span class="self">self</span>.<span class="ident">len</span>() }
}
</pre>

<p>The implementation has to explicitly declare the type parameter that
it binds, <code>T</code>, before using it to specify its trait type. Rust
requires this declaration because the <code>impl</code> could also, for example,
specify an implementation of <code>Seq&lt;int&gt;</code>. The trait type (appearing
between <code>impl</code> and <code>for</code>) <em>refers</em> to a type, rather than
defining one.</p>

<p>The type parameters bound by a trait are in scope in each of the
method declarations. So, re-declaring the type parameter
<code>T</code> as an explicit type parameter for <code>length</code>, in either the trait or
the impl, would be a compile-time error.</p>

<p>Within a trait definition, <code>Self</code> is a special type that you can think
of as a type parameter. An implementation of the trait for any given
type <code>T</code> replaces the <code>Self</code> type parameter with <code>T</code>. The following
trait describes types that support an equality operation:</p>
<pre class="rust "><span class="comment">// In a trait, `self` refers to the self argument.
// `Self` refers to the type implementing the trait.
</span><span class="kw">trait</span> <span class="ident">Eq</span> {
    <span class="kw">fn</span> <span class="ident">equals</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">other</span>: <span class="kw-2">&amp;</span><span class="ident">Self</span>) <span class="op">-&gt;</span> <span class="ident">bool</span>;
}<span class="comment">

// In an impl, `self` refers just to the value of the receiver
</span><span class="kw">impl</span> <span class="ident">Eq</span> <span class="kw">for</span> <span class="ident">int</span> {
    <span class="kw">fn</span> <span class="ident">equals</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">other</span>: <span class="kw-2">&amp;</span><span class="ident">int</span>) <span class="op">-&gt;</span> <span class="ident">bool</span> { <span class="op">*</span><span class="ident">other</span> <span class="op">==</span> <span class="op">*</span><span class="self">self</span> }
}
</pre>

<p>Notice that in the trait definition, <code>equals</code> takes a
second parameter of type <code>Self</code>.
In contrast, in the <code>impl</code>, <code>equals</code> takes a second parameter of
type <code>int</code>, only using <code>self</code> as the name of the receiver.</p>

<p>Just as in type implementations, traits can define standalone (static)
methods.  These methods are called by prefixing the method name with the trait
name and a double colon.  The compiler uses type inference to decide which
implementation to use.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span>;
<span class="kw">trait</span> <span class="ident">Shape</span> { <span class="kw">fn</span> <span class="ident">new</span>(<span class="ident">area</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">Self</span>; }
<span class="kw">struct</span> <span class="ident">Circle</span> { <span class="ident">radius</span>: <span class="ident">f64</span> }
<span class="kw">struct</span> <span class="ident">Square</span> { <span class="ident">length</span>: <span class="ident">f64</span> }

<span class="kw">impl</span> <span class="ident">Shape</span> <span class="kw">for</span> <span class="ident">Circle</span> {
    <span class="kw">fn</span> <span class="ident">new</span>(<span class="ident">area</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">Circle</span> { <span class="ident">Circle</span> { <span class="ident">radius</span>: (<span class="ident">area</span> <span class="op">/</span> <span class="ident">PI</span>).<span class="ident">sqrt</span>() } }
}
<span class="kw">impl</span> <span class="ident">Shape</span> <span class="kw">for</span> <span class="ident">Square</span> {
    <span class="kw">fn</span> <span class="ident">new</span>(<span class="ident">area</span>: <span class="ident">f64</span>) <span class="op">-&gt;</span> <span class="ident">Square</span> { <span class="ident">Square</span> { <span class="ident">length</span>: <span class="ident">area</span>.<span class="ident">sqrt</span>() } }
}

<span class="kw">let</span> <span class="ident">area</span> <span class="op">=</span> <span class="number">42.5</span>;
<span class="kw">let</span> <span class="ident">c</span>: <span class="ident">Circle</span> <span class="op">=</span> <span class="ident">Shape</span>::<span class="ident">new</span>(<span class="ident">area</span>);
<span class="kw">let</span> <span class="ident">s</span>: <span class="ident">Square</span> <span class="op">=</span> <span class="ident">Shape</span>::<span class="ident">new</span>(<span class="ident">area</span>);
</pre>

<h2 id="bounded-type-parameters-and-static-method-dispatch" class="section-header"><a href="#bounded-type-parameters-and-static-method-dispatch">17.5 Bounded type parameters and static method dispatch(绑定类型参数和静态方法调度)</a></h2>
<p>Traits give us a language for defining predicates on types, or
abstract properties that types can have. We can use this language to
define <em>bounds</em> on type parameters, so that we can then operate on
generic types.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">print_all</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Printable</span><span class="op">&gt;</span>(<span class="ident">printable_things</span>: <span class="kw-2">~</span>[<span class="ident">T</span>]) {
    <span class="kw">for</span> <span class="ident">thing</span> <span class="kw">in</span> <span class="ident">printable_things</span>.<span class="ident">iter</span>() {
        <span class="ident">thing</span>.<span class="ident">print</span>();
    }
}
</pre>

<p>Declaring <code>T</code> as conforming to the <code>Printable</code> trait (as we earlier
did with <code>Clone</code>) makes it possible to call methods from that trait
on values of type <code>T</code> inside the function. It will also cause a
compile-time error when anyone tries to call <code>print_all</code> on a vector
whose element type does not have a <code>Printable</code> implementation.</p>

<p>Type parameters can have multiple bounds by separating them with <code>+</code>,
as in this version of <code>print_all</code> that copies elements.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">print_all</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Printable</span> <span class="op">+</span> <span class="ident">Clone</span><span class="op">&gt;</span>(<span class="ident">printable_things</span>: <span class="kw-2">~</span>[<span class="ident">T</span>]) {
    <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">i</span> <span class="op">=</span> <span class="number">0</span>;
    <span class="kw">while</span> <span class="ident">i</span> <span class="op">&lt;</span> <span class="ident">printable_things</span>.<span class="ident">len</span>() {
        <span class="kw">let</span> <span class="ident">copy_of_thing</span> <span class="op">=</span> <span class="ident">printable_things</span>[<span class="ident">i</span>].<span class="ident">clone</span>();
        <span class="ident">copy_of_thing</span>.<span class="ident">print</span>();
        <span class="ident">i</span> <span class="op">+=</span> <span class="number">1</span>;
    }
}
</pre>

<p>Method calls to bounded type parameters are <em>statically dispatched</em>,
imposing no more overhead than normal function invocation, so are
the preferred way to use traits polymorphically.</p>

<p>This usage of traits is similar to Haskell type classes.</p>

<h2 id="trait-objects-and-dynamic-method-dispatch" class="section-header"><a href="#trait-objects-and-dynamic-method-dispatch">17.6 Trait objects and dynamic method dispatch(特性对象和动态方法调度)</a></h2>
<p>The above allows us to define functions that polymorphically act on
values of a single unknown type that conforms to a given trait.
However, consider this function:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Drawable</span> { <span class="kw">fn</span> <span class="ident">draw</span>(<span class="kw-2">&amp;</span><span class="self">self</span>); }

<span class="kw">fn</span> <span class="ident">draw_all</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Drawable</span><span class="op">&gt;</span>(<span class="ident">shapes</span>: <span class="kw-2">~</span>[<span class="ident">T</span>]) {
    <span class="kw">for</span> <span class="ident">shape</span> <span class="kw">in</span> <span class="ident">shapes</span>.<span class="ident">iter</span>() { <span class="ident">shape</span>.<span class="ident">draw</span>(); }
}
</pre>

<p>You can call that on a vector of circles, or a vector of rectangles
(assuming those have suitable <code>Drawable</code> traits defined), but not on
a vector containing both circles and rectangles. When such behavior is
needed, a trait name can alternately be used as a type, called
an <em>object</em>.</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">draw_all</span>(<span class="ident">shapes</span>: <span class="kw-2">&amp;</span>[<span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Drawable</span><span class="op">&gt;</span>]) {
    <span class="kw">for</span> <span class="ident">shape</span> <span class="kw">in</span> <span class="ident">shapes</span>.<span class="ident">iter</span>() { <span class="ident">shape</span>.<span class="ident">draw</span>(); }
}
</pre>

<p>In this example, there is no type parameter. Instead, the <code>~Drawable</code>
type denotes any owned box value that implements the <code>Drawable</code> trait.
To construct such a value, you use the <code>as</code> operator to cast a value
to an object:</p>
<pre class="rust ">
<span class="kw">impl</span> <span class="ident">Drawable</span> <span class="kw">for</span> <span class="ident">Circle</span> { <span class="kw">fn</span> <span class="ident">draw</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) {<span class="comment"> /* ... */ </span>} }
<span class="kw">impl</span> <span class="ident">Drawable</span> <span class="kw">for</span> <span class="ident">Rectangle</span> { <span class="kw">fn</span> <span class="ident">draw</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) {<span class="comment"> /* ... */ </span>} }

<span class="kw">let</span> <span class="ident">c</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Circle</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">new_circle</span>();
<span class="kw">let</span> <span class="ident">r</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Rectangle</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">new_rectangle</span>();
<span class="ident">draw_all</span>([<span class="ident">c</span> <span class="kw">as</span> <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Drawable</span><span class="op">&gt;</span>, <span class="ident">r</span> <span class="kw">as</span> <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Drawable</span><span class="op">&gt;</span>]);
</pre>

<p>We omit the code for <code>new_circle</code> and <code>new_rectangle</code>; imagine that
these just return <code>Circle</code>s and <code>Rectangle</code>s with a default size. Note
that, like strings and vectors, objects have dynamic size and may
only be referred to via one of the pointer types.
Other pointer types work as well.
Casts to traits may only be done with compatible pointers so,
for example, an <code>&amp;Circle</code> may not be cast to a <code>Box&lt;Drawable&gt;</code>.</p>
<pre class="rust "><span class="comment">// An owned object
</span><span class="kw">let</span> <span class="ident">owny</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Drawable</span><span class="op">&gt;</span> <span class="op">=</span> <span class="kw">box</span> <span class="ident">new_circle</span>() <span class="kw">as</span> <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Drawable</span><span class="op">&gt;</span>;<span class="comment">
// A borrowed object
</span><span class="kw">let</span> <span class="ident">stacky</span>: <span class="kw-2">&amp;</span><span class="ident">Drawable</span> <span class="op">=</span> <span class="kw-2">&amp;</span><span class="ident">new_circle</span>() <span class="kw">as</span> <span class="kw-2">&amp;</span><span class="ident">Drawable</span>;
</pre>

<p>Method calls to trait types are <em>dynamically dispatched</em>. Since the
compiler doesn't know specifically which functions to call at compile
time, it uses a lookup table (also known as a vtable or dictionary) to
select the method to call at runtime.</p>

<p>This usage of traits is similar to Java interfaces.</p>

<p>There are some built-in bounds, such as <code>Send</code> and <code>Share</code>, which are properties
of the components of types. By design, trait objects don't know the exact type
of their contents and so the compiler cannot reason about those properties.</p>

<p>You can instruct the compiler, however, that the contents of a trait object must
acribe to a particular bound with a trailing colon (<code>:</code>). These are examples of
valid types:</p>
<pre class="rust "><span class="kw">trait</span> <span class="ident">Foo</span> {}
<span class="kw">trait</span> <span class="ident">Bar</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span> {}

<span class="kw">fn</span> <span class="ident">sendable_foo</span>(<span class="ident">f</span>: <span class="ident">Box</span><span class="op">&lt;</span><span class="ident">Foo</span>:<span class="ident">Send</span><span class="op">&gt;</span>) {<span class="comment"> /* ... */ </span>}
<span class="kw">fn</span> <span class="ident">shareable_bar</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Share</span><span class="op">&gt;</span>(<span class="ident">b</span>: <span class="kw-2">&amp;</span><span class="ident">Bar</span><span class="op">&lt;</span><span class="ident">T</span><span class="op">&gt;</span>: <span class="ident">Share</span>) {<span class="comment"> /* ... */ </span>}
</pre>

<p>When no colon is specified (such as the type <code>~Foo</code>), it is inferred that the
value ascribes to no bounds. They must be added manually if any bounds are
necessary for usage.</p>

<p>Builtin kind bounds can also be specified on closure types in the same way (for
example, by writing <code>fn:Send()</code>), and the default behaviours are the same as
for traits of the same storage class.</p>

<h2 id="trait-inheritance" class="section-header"><a href="#trait-inheritance">17.7 Trait inheritance(特性继承)</a></h2>
<p>We can write a trait declaration that <em>inherits</em> from other traits, called <em>supertraits</em>.
Types that implement a trait must also implement its supertraits.
For example,
we can define a <code>Circle</code> trait that inherits from <code>Shape</code>.</p>
	我们可以编写特性声明从其他的特性继承,叫做supertraits.在这个特性上实现的方法也必须在它的supertraits上实现:
<pre class="rust "><span class="kw">trait</span> <span class="ident">Shape</span> { <span class="kw">fn</span> <span class="ident">area</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">f64</span>; }
<span class="kw">trait</span> <span class="ident">Circle</span> : <span class="ident">Shape</span> { <span class="kw">fn</span> <span class="ident">radius</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">f64</span>; }
</pre>

<p>Now, we can implement <code>Circle</code> on a type only if we also implement <code>Shape</code>.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span>;
<span class="kw">struct</span> <span class="ident">CircleStruct</span> { <span class="ident">center</span>: <span class="ident">Point</span>, <span class="ident">radius</span>: <span class="ident">f64</span> }
<span class="kw">impl</span> <span class="ident">Circle</span> <span class="kw">for</span> <span class="ident">CircleStruct</span> {
    <span class="kw">fn</span> <span class="ident">radius</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> { (<span class="self">self</span>.<span class="ident">area</span>() <span class="op">/</span> <span class="ident">PI</span>).<span class="ident">sqrt</span>() }
}
<span class="kw">impl</span> <span class="ident">Shape</span> <span class="kw">for</span> <span class="ident">CircleStruct</span> {
    <span class="kw">fn</span> <span class="ident">area</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> { <span class="ident">PI</span> <span class="op">*</span> <span class="ident">square</span>(<span class="self">self</span>.<span class="ident">radius</span>) }
}
</pre>

<p>Notice that methods of <code>Circle</code> can call methods on <code>Shape</code>, as our
<code>radius</code> implementation calls the <code>area</code> method.
This is a silly way to compute the radius of a circle
(since we could just return the <code>radius</code> field), but you get the idea.</p>

<p>In type-parameterized functions,
methods of the supertrait may be called on values of subtrait-bound type parameters.
Refering to the previous example of <code>trait Circle : Shape</code>:</p>
<pre class="rust "><span class="kw">fn</span> <span class="ident">radius_times_area</span><span class="op">&lt;</span><span class="ident">T</span>: <span class="ident">Circle</span><span class="op">&gt;</span>(<span class="ident">c</span>: <span class="ident">T</span>) <span class="op">-&gt;</span> <span class="ident">f64</span> {<span class="comment">
    // `c` is both a Circle and a Shape
    </span><span class="ident">c</span>.<span class="ident">radius</span>() <span class="op">*</span> <span class="ident">c</span>.<span class="ident">area</span>()
}
</pre>

<p>Likewise, supertrait methods may also be called on trait objects.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">f64</span>::<span class="ident">consts</span>::<span class="ident">PI</span>;

<span class="kw">let</span> <span class="ident">concrete</span> <span class="op">=</span> <span class="kw-2">~</span><span class="ident">CircleStruct</span>{<span class="ident">center</span>:<span class="ident">Point</span>{<span class="ident">x</span>:<span class="number">3.0</span>,<span class="ident">y</span>:<span class="number">4.0</span>},<span class="ident">radius</span>:<span class="number">5.0</span>};
<span class="kw">let</span> <span class="ident">mycircle</span>: <span class="kw-2">~</span><span class="ident">Circle</span> <span class="op">=</span> <span class="ident">concrete</span> <span class="kw">as</span> <span class="kw-2">~</span><span class="ident">Circle</span>;
<span class="kw">let</span> <span class="ident">nonsense</span> <span class="op">=</span> <span class="ident">mycircle</span>.<span class="ident">radius</span>() <span class="op">*</span> <span class="ident">mycircle</span>.<span class="ident">area</span>();
</pre>

<blockquote>
<p><em>Note:</em> Trait inheritance does not actually work with objects yet</p>
</blockquote>

<h2 id="deriving-implementations-for-traits" class="section-header"><a href="#deriving-implementations-for-traits">17.8 Deriving implementations for traits(特性派生实现)</a></h2>
<p>A small number of traits in <code>std</code> and <code>extra</code> can have implementations
that can be automatically derived. These instances are specified by
placing the <code>deriving</code> attribute on a data type declaration. For
example, the following will mean that <code>Circle</code> has an implementation
for <code>Eq</code> and can be used with the equality operators, and that a value
of type <code>ABC</code> can be randomly generated and converted to a string:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">rand</span>;

<span class="attribute">#[<span class="ident">deriving</span>(<span class="ident">Eq</span>)]</span>
<span class="kw">struct</span> <span class="ident">Circle</span> { <span class="ident">radius</span>: <span class="ident">f64</span> }

<span class="attribute">#[<span class="ident">deriving</span>(<span class="ident">Rand</span>, <span class="ident">Show</span>)]</span>
<span class="kw">enum</span> <span class="ident">ABC</span> { <span class="ident">A</span>, <span class="ident">B</span>, <span class="ident">C</span> }

<span class="kw">fn</span> <span class="ident">main</span>() {<span class="comment">
    // Use the Show trait to print "A, B, C."
    </span><span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}, {}, {}"</span>, <span class="ident">A</span>, <span class="ident">B</span>, <span class="ident">C</span>);
}
</pre>

<p>The full list of derivable traits is <code>Eq</code>, <code>TotalEq</code>, <code>Ord</code>,
<code>TotalOrd</code>, <code>Encodable</code> <code>Decodable</code>, <code>Clone</code>,
<code>Hash</code>, <code>Rand</code>, <code>Default</code>, <code>Zero</code>, <code>FromPrimitive</code> and <code>Show</code>.</p>

<h1 id="crates-and-the-module-system" class="section-header"><a href="#crates-and-the-module-system">18 Crates and the module system(Crate和模块系统)</a></h1>
<p>Rust's module system is very powerful, but because of that also somewhat complex.
Nevertheless, this section will try to explain every important aspect of it.</p>
Rust模块系统是非常强大,因此也有些复杂.虽说如此,本章将试图解释清楚每一个重要的方面.
<h2 id="crates" class="section-header"><a href="#crates">18.1 Crates</a></h2>
<p>In order to speak about the module system, we first need to define the medium it exists in:</p>
为了谈论模块系统,我们首先需要定义它存在的媒介:
<p>Let's say you've written a program or a library, compiled it, and got the resulting binary.
In Rust, the content of all source code that the compiler directly had to compile in order to end up with
that binary is collectively called a 'crate'.</p>
你已经写了一个程序或者一个库,编译并且得到二进制结果.在Rust里,所有源代码的内容被编译器编译产生二进制统称为
'crate'(有箱子的意思)
<p>For example, for a simple hello world program your crate only consists of this code:</p>
如例:简单的hello world 程序 你的crate仅需要如下代码:
<pre class="rust "><span class="comment">// `main.rs`
</span><span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Hello world!"</span>);
}
</pre>

<p>A crate is also the unit of independent compilation in Rust: <code>rustc</code> always compiles a single crate at a time,
from which it produces either a library or an executable.</p>
一个crate也是Rust里独立编译的单元,Rustc总是一次编译一个单一的crate不管是在编译执行文件或者是库文件.
<p>Note that merely using an already compiled library in your code does not make it part of your crate.</p>
请注意，仅仅是使用一个已经编译的库中的代码不会成为你的crate的一部分
<h2 id="the-module-hierarchy" class="section-header"><a href="#the-module-hierarchy">18.2 The module hierarchy(模块系统)</a></h2>
<p>For every crate, all the code in it is arranged in a hierarchy of modules starting with a single
root module. That root module is called the 'crate root'.</p>
对每一个create,所以代码在模块层次里布置成从单一根模块开始.这个根模块被叫做"crate root"
<p>All modules in a crate below the crate root are declared with the <code>mod</code> keyword:</p>
crate里所有的在crate root下的模块都是以mod关键词声明开始:

<pre class="rust "><span class="comment">// This is the crate root
</span><span class="kw">mod</span> <span class="ident">farm</span> {<span class="comment">
    // This is the body of module 'farm' declared in the crate root.

    </span><span class="kw">fn</span> <span class="ident">chicken</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"cluck cluck"</span>); }
    <span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"mooo"</span>); }

    <span class="kw">mod</span> <span class="ident">barn</span> {<span class="comment">
        // Body of module 'barn'

        </span><span class="kw">fn</span> <span class="ident">hay</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"..."</span>); }
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Hello farm!"</span>);
}
</pre>

<p>As you can see, your module hierarchy is now three modules deep: There is the crate root, which contains your <code>main()</code>
function, and the module <code>farm</code>. The module <code>farm</code> also contains two functions and a third module <code>barn</code>,
which contains a function <code>hay</code>.</p>
如你所见,模块层次现在是三个模块深度:crate root包含你main函数和模块farm.模块farm包含2个函数和第三个模块barn,
模块barn包含函数hay.
<h2 id="paths-and-visibility" class="section-header"><a href="#paths-and-visibility">18.3 Paths and visibility(路径和可见性)</a></h2>
<p>We've now defined a nice module hierarchy. But how do we access the items in it from our <code>main</code> function?
One way to do it is to simply fully qualifying it:</p>
我们现在已经顶一个很好的模块层次.那么我们如何在main函数里能访问到这些项目呢?<br/>
一个简单方法是通过完全的修饰路径:
<pre class="rust "><span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">fn</span> <span class="ident">chicken</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"cluck cluck"</span>); }<span class="comment">
    // ...
</span>}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Hello chicken!"</span>);

    ::<span class="ident">farm</span>::<span class="ident">chicken</span>();<span class="comment"> // Won't compile yet, see further down
</span>}
</pre>

<p>The <code>::farm::chicken</code> construct is what we call a 'path'.</p>
::farm::chicken 这种结构表达我们称呼为'路径'。
<p>Because it's starting with a <code>::</code>, it's also a 'global path', which qualifies
an item by its full path in the module hierarchy relative to the crate root.</p>
由于它开始::，也称之为'全局路径',这个修饰是从项目在模块层次里相对到crate root的路径.
<p>If the path were to start with a regular identifier, like <code>farm::chicken</code>, it
would be a 'local path' instead. We'll get to them later.</p>
如果路径开始为正常的限定符,比如farm::chicken,这一般是用本地路径代替了，后面说明这个。
<p>Now, if you actually tried to compile this code example, you'll notice that you
get a <code>function 'chicken' is private</code> error. That's because by default, items
(<code>fn</code>, <code>struct</code>, <code>static</code>, <code>mod</code>, ...) are private.</p>
现在,如果你实际试图编译这个代码例子,你会注意到你得到一个function 'chicken' is private的错误。
因为默认项目的可见性都是私有的包括(fn,struct,static,mod).
<p>To make them visible outside their containing modules, you need to mark them
<em>public</em> with <code>pub</code>:</p>
	要想使这些项目对包含它们模块从外部可见,你必须标注这些项目为公开的通过pub关键词.
<pre class="rust "><span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">chicken</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"cluck cluck"</span>); }
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"mooo"</span>); }<span class="comment">
    // ...
</span>}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Hello chicken!"</span>);
    ::<span class="ident">farm</span>::<span class="ident">chicken</span>();<span class="comment"> // This compiles now
</span>}
</pre>

<p>Visibility restrictions in Rust exist only at module boundaries. This
is quite different from most object-oriented languages that also
enforce restrictions on objects themselves. That's not to say that
Rust doesn't support encapsulation: both struct fields and methods can
be private. But this encapsulation is at the module level, not the
struct level.</p>
Rust可见性的限制仅仅存在于模块边界上.这是和绝大多数面向对象语言非常不同的地方.
面向对象语言也在对象自身上执行约束.这不是说Rust不支持封装:struct的字段和方法都可以是私有的.
但是这个封装只是在模块级别,而不是在struct 级别.字段默认是私有的(private),可以通过pub关键词使它为公开的.
<p>Fields are <em>private</em> by default, and can be made <em>public</em> with
the <code>pub</code> keyword:</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">pub</span> <span class="kw">struct</span> <span class="ident">Farm</span> {
        <span class="ident">chickens</span>: <span class="kw-2">~</span>[<span class="ident">Chicken</span>],
        <span class="kw">pub</span> <span class="ident">farmer</span>: <span class="ident">Human</span>
    }

    <span class="kw">impl</span> <span class="ident">Farm</span> {
        <span class="kw">fn</span> <span class="ident">feed_chickens</span>(<span class="kw-2">&amp;</span><span class="self">self</span>) {<span class="comment"> /* ... */ </span>}
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">add_chicken</span>(<span class="kw-2">&amp;</span><span class="self">self</span>, <span class="ident">c</span>: <span class="ident">Chicken</span>) {<span class="comment"> /* ... */ </span>}
    }

    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">feed_animals</span>(<span class="ident">farm</span>: <span class="kw-2">&amp;</span><span class="ident">Farm</span>) {
        <span class="ident">farm</span>.<span class="ident">feed_chickens</span>();
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="kw">let</span> <span class="ident">f</span> <span class="op">=</span> <span class="ident">make_me_a_farm</span>();
    <span class="ident">f</span>.<span class="ident">add_chicken</span>(<span class="ident">make_me_a_chicken</span>());
    <span class="ident">farm</span>::<span class="ident">feed_animals</span>(<span class="kw-2">&amp;</span><span class="ident">f</span>);
    <span class="ident">f</span>.<span class="ident">farmer</span>.<span class="ident">rest</span>();<span class="comment">

    // This wouldn't compile because both are private:
    // `f.feed_chickens();`
    // `let chicken_counter = f.chickens.len();`
</span>}
</pre>

<p>Exact details and specifications about visibility rules can be found in the Rust
manual.</p>
关于可见性规则更加准确的细节和规范可以在Rust手册中查看.<a href=http://static.rust-lang.org/doc/master/rust.html#visibility-and-privacy target=_blank>6.2 Visibility and Privacy(可见性和隐私)</a>
<h2 id="files-and-modules" class="section-header"><a href="#files-and-modules">18.4 Files and modules(文件和模块)</a></h2>
<p>One important aspect of Rust's module system is that source files and
 modules are not the same thing. You define a module hierarchy, populate
 it with all your definitions, define visibility, maybe put in a <code>fn main()</code>, and that's it.</p>
Rust模块一个重要的方面是源文件和模块不是同一个事情.你定义一个模块层次,用定义来填充,定义可见性也许函数fn main()中使用.
<p>The only file that's relevant when compiling is the one that contains the body
of your crate root, and it's only relevant because you have to pass that file
to <code>rustc</code> to compile your crate.</p>
编译时唯一相应的文件是包含你的crate root主体的文件,并且它也唯一相应的你传递给rustc用来编译你的crate的文件
<p>In principle, that's all you need: You can write any Rust program as one giant source file that contains your
crate root and everything else in <code>mod ... { ... }</code> declarations.</p>
原则上，这是所有你需要的:你可以写任何Rust程序在一个巨大的源文件里包含你的crate root和其他所有的模块声明.
<p>However, in practice you usually want to split up your code into multiple
source files to make it more manageable. Rust allows you to move the body of
any module into its own source file. If you declare a module without its body,
like <code>mod foo;</code>, the compiler will look for the files <code>foo.rs</code> and <code>foo/mod.rs</code>
inside some directory (usually the same as of the source file containing the
<code>mod foo;</code> declaration). If it finds either, it uses the content of that file
as the body of the module. If it finds both, that's a compile error.</p>
当然，在实际中,一般是要吧代码分开到多个文件中方便管理.Rust允许你移动任何模块的主体道它子集的源文件中.如果你声明一个模块但没有主体<br>
比如mod foo;那么编译器将会寻找文件foo.rs和foo/mod.rs在一些目录里(一般是和包含mod foo;声明的源文件一个目录).如果它发现两者之一,它将使用
该文件的内容作为模块的主体.如果它同时发现2个文件，则出现编译错误.
<p>To move the content of <code>mod farm</code> into its own file, you can write:</p>

<pre class="rust "><span class="comment">// `main.rs` - contains body of the crate root
</span><span class="kw">mod</span> <span class="ident">farm</span>;<span class="comment"> // Compiler will look for `farm.rs` and `farm/mod.rs`

</span><span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Hello farm!"</span>);
    ::<span class="ident">farm</span>::<span class="ident">cow</span>();
}
</pre>
<pre class="rust "><span class="comment">// `farm.rs` - contains body of module 'farm' in the crate root
</span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">chicken</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"cluck cluck"</span>); }
<span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"mooo"</span>); }

<span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">barn</span> {
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">hay</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"..."</span>); }
}
</pre>

<p>In short, <code>mod foo;</code> is just syntactic sugar for <code>mod foo { /* content of &lt;...&gt;/foo.rs or &lt;...&gt;/foo/mod.rs */ }</code>.</p>
短语mod foo;可以看作是语法糖mod foo{}
<p>This also means that having two or more identical <code>mod foo;</code> declarations
somewhere in your crate hierarchy is generally a bad idea,
just like copy-and-paste-ing a module into multiple places is a bad idea.
Both will result in duplicate and mutually incompatible definitions.</p>
这也意味着如果有2个或者更多个mod foo声明符出现在你的crate层次里一般来说是个坏主意.就如同复制粘贴模块
到多个地方是个坏主意一样.这也会出现重复和可变的不兼容的定义.
<p>When <code>rustc</code> resolves these module declarations, it starts by looking in the
parent directory of the file containing the <code>mod foo</code> declaration. For example,
given a file with the module body:</p>
当rustc解析完这些模块声明后,它开始从父目录开始寻找包含mod foo的文件.比如:
文件包含这些模块的主体:
<pre class="rust "><span class="comment">// `src/main.rs`
</span><span class="kw">mod</span> <span class="ident">plants</span>;
<span class="kw">mod</span> <span class="ident">animals</span> {
    <span class="kw">mod</span> <span class="ident">fish</span>;
    <span class="kw">mod</span> <span class="ident">mammals</span> {
        <span class="kw">mod</span> <span class="ident">humans</span>;
    }
}
</pre>

<p>The compiler will look for these files, in this order:</p>
编译器将会按照下面的目录和文件顺序寻找:
<pre><code class="language-{.notrust}">src/plants.rs
src/plants/mod.rs

src/animals/fish.rs
src/animals/fish/mod.rs

src/animals/mammals/humans.rs
src/animals/mammals/humans/mod.rs</code></pre>

<p>Keep in mind that identical module hierarchies can still lead to different path
lookups depending on how and where you've moved a module body to its own file.
For example, if you move the <code>animals</code> module into its own file:</p>
要时刻提醒自己相同的模块层次可以导致不同的路径搜索,这要看你怎样和如何防止模块主体文件:
<pre class="rust "><span class="comment">// `src/main.rs`
</span><span class="kw">mod</span> <span class="ident">plants</span>;
<span class="kw">mod</span> <span class="ident">animals</span>;
</pre>
<pre class="rust "><span class="comment">// `src/animals.rs` or `src/animals/mod.rs`
</span><span class="kw">mod</span> <span class="ident">fish</span>;
<span class="kw">mod</span> <span class="ident">mammals</span> {
    <span class="kw">mod</span> <span class="ident">humans</span>;
}
</pre>

<p>...then the source files of <code>mod animals</code>'s submodules can
 either be in the same directory as the animals source file or in a 
subdirectory of its directory. If the animals file is <code>src/animals.rs</code>, <code>rustc</code> will look for:</p>
此时mod animals的子模块的源文件就可以放在和animas源文件同一个目录或者它的子目录下.
如果animals文件是<code>src/animals.rs</code>,rustc将会这样寻找其他模块:
<pre><code class="language-{.notrust}">src/animals.rs
    src/fish.rs
    src/fish/mod.rs

    src/mammals/humans.rs
    src/mammals/humans/mod.rs</code></pre>

<p>If the animals file is <code>src/animals/mod.rs</code>, <code>rustc</code> will look for:</p>
如果animals文件是 <code>src/animals/mod.rs</code>,rustc会这样寻找:
<pre><code class="language-{.notrust}">src/animals/mod.rs
    src/animals/fish.rs
    src/animals/fish/mod.rs

    src/animals/mammals/humans.rs
    src/animals/mammals/humans/mod.rs
</code></pre>

<p>These rules allow you to write small modules consisting of single 
source files which can live in the same directory as well as large 
modules which group submodule source files in subdirectories.</p>
这些规则允许你写一个比较的模块所有的源文件都在同一个目录下，或者一个比较大的模块,可以分组
子模块源代码在子目录下.
<p>If you need to override where <code>rustc</code> will look for the file containing a
module's source code, use the <code>path</code> compiler directive. For example, to load a
<code>classified</code> module from a different file:</p>
<pre class="rust "><span class="attribute">#[<span class="ident">path</span><span class="op">=</span><span class="string">"../../area51/alien.rs"</span>]</span>
<span class="kw">mod</span> <span class="ident">classified</span>;
</pre>

<h2 id="importing-names-into-the-local-scope" class="section-header"><a href="#importing-names-into-the-local-scope">18.5 Importing names into the local scope(在局部范围引进名字)</a></h2>
<p>Always referring to definitions in other modules with their global
path gets old really fast, so Rust has a way to import
them into the local scope of your module: <code>use</code>-statements.</p>

<p>They work like this: At the beginning of any module body, <code>fn</code> body, or any other block
you can write a list of <code>use</code>-statements, consisting of the keyword <code>use</code> and a <strong>global path</strong> to an item
without the <code>::</code> prefix. For example, this imports <code>cow</code> into the local scope:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">cow</span>;
</pre>

<p>The path you give to <code>use</code> is per default global, meaning relative to the crate root,
no matter how deep the module hierarchy is, or whether the module body it's written in
is contained in its own file. (Remember: files are irrelevant.)</p>

<p>This is different from other languages, where you often only find a single import construct that combines the semantic
of <code>mod foo;</code> and <code>use</code>-statements, and which tend to work relative to the source file or use an absolute file path
- Ruby's <code>require</code> or C/C++'s <code>#include</code> come to mind.</p>

<p>However, it's also possible to import things relative to the module of the <code>use</code>-statement:
Adding a <code>super::</code> in front of the path will start in the parent module,
while adding a <code>self::</code> prefix will start in the current module:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">super</span>::<span class="ident">some_parent_item</span>;
<span class="kw">use</span> <span class="self">self</span>::<span class="ident">some_child_module</span>::<span class="ident">some_item</span>;
</pre>

<p>Again - relative to the module, not to the file.</p>

<p>Imports are also shadowed by local definitions:
For each name you mention in a module/block, <code>rust</code>
will first look at all items that are defined locally,
and only if that results in no match look at items you brought in
scope with corresponding <code>use</code> statements.</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">cow</span>;<span class="comment">
// ...
</span><span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Mooo!"</span>) }

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="ident">cow</span>()<span class="comment"> // resolves to the locally defined `cow()` function
</span>}
</pre>

<p>To make this behavior more obvious, the rule has been made that <code>use</code>-statement always need to be written
before any declaration, like in the example above. This is a purely artificial rule introduced
because people always assumed they shadowed each other based on order, despite the fact that all items in rust are
mutually recursive, order independent definitions.</p>

<p>One odd consequence of that rule is that <code>use</code> statements also go in front of any <code>mod</code> declaration,
even if they refer to things inside them:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">cow</span>;
<span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Moooooo?"</span>) }
}

<span class="kw">fn</span> <span class="ident">main</span>() { <span class="ident">cow</span>() }
</pre>

<p>This is what our <code>farm</code> example looks like with <code>use</code> statements:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">chicken</span>;
<span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">cow</span>;
<span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">barn</span>;

<span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">chicken</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"cluck cluck"</span>); }
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"mooo"</span>); }

    <span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">barn</span> {
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">hay</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"..."</span>); }
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Hello farm!"</span>);<span class="comment">

    // Can now refer to those names directly:
    </span><span class="ident">chicken</span>();
    <span class="ident">cow</span>();
    <span class="ident">barn</span>::<span class="ident">hay</span>();
}
</pre>

<p>And here an example with multiple files:</p>
<pre class="rust "><span class="comment">// `a.rs` - crate root
</span><span class="kw">use</span> <span class="ident">b</span>::<span class="ident">foo</span>;
<span class="kw">use</span> <span class="ident">b</span>::<span class="ident">c</span>::<span class="ident">bar</span>;
<span class="kw">mod</span> <span class="ident">b</span>;
<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="ident">foo</span>();
    <span class="ident">bar</span>();
}
</pre>
<pre class="rust "><span class="comment">// `b/mod.rs`
</span><span class="kw">pub</span> <span class="kw">mod</span> <span class="ident">c</span>;
<span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">foo</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Foo!"</span>; }
</pre>
<pre class="rust "><span class="comment">// `b/c.rs`
</span><span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">bar</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Bar!"</span>); }
</pre>

<p>There also exist two short forms for importing multiple names at once:</p>

<ol>
<li>Explicit mention multiple names as the last element of an <code>use</code> path:</li>
</ol>
<pre class="rust "><span class="kw">use</span> <span class="ident">farm</span>::{<span class="ident">chicken</span>, <span class="ident">cow</span>};
</pre>

<ol>
<li>Import everything in a module with a wildcard:</li>
</ol>
<pre class="rust "><span class="kw">use</span> <span class="ident">farm</span>::<span class="op">*</span>;
</pre>

<blockquote>
<p><em>Note:</em> This feature of the compiler is currently gated behind the
<code>#![feature(globs)]</code> directive. More about these directives can be found in
the manual.</p>
</blockquote>

<p>However, that's not all. You can also rename an item while you're bringing it into scope:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">egg_layer</span> <span class="op">=</span> <span class="ident">farm</span>::<span class="ident">chicken</span>;<span class="comment">
// ...

</span><span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="ident">egg_layer</span>();
}
</pre>

<p>In general, <code>use</code> creates a local alias:
An alternate path and a possibly different name to access the same item,
without touching the original, and with both being interchangeable.</p>

<h2 id="reexporting-names" class="section-header"><a href="#reexporting-names">18.6 Reexporting names(重新输出名字)</a></h2>
<p>It is also possible to reexport items to be accessible under your module.</p>

<p>For that, you write <code>pub use</code>:</p>
<pre class="rust "><span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">pub</span> <span class="kw">use</span> <span class="self">self</span>::<span class="ident">barn</span>::<span class="ident">hay</span>;

    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">chicken</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"cluck cluck"</span>); }
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">cow</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"mooo"</span>); }

    <span class="kw">mod</span> <span class="ident">barn</span> {
        <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">hay</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"..."</span>); }
    }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="ident">farm</span>::<span class="ident">chicken</span>();
    <span class="ident">farm</span>::<span class="ident">cow</span>();
    <span class="ident">farm</span>::<span class="ident">hay</span>();
}
</pre>

<p>Just like in normal <code>use</code> statements, the exported names
merely represent an alias to the same thing and can also be renamed.</p>

<p>The above example also demonstrate what you can use <code>pub use</code> for:
The nested <code>barn</code> module is private, but the <code>pub use</code> allows users
of the module <code>farm</code> to access a function from <code>barn</code> without needing
to know that <code>barn</code> exists.</p>

<p>In other words, you can use it to decouple a public api from its internal implementation.</p>

<h2 id="using-libraries" class="section-header"><a href="#using-libraries">18.7 Using libraries(使用库)</a></h2>
<p>So far we've only talked about how to define and structure your own crate.</p>

<p>However, most code out there will want to use preexisting libraries,
as there really is no reason to start from scratch each time you start a new project.</p>

<p>In Rust terminology, we need a way to refer to other crates.</p>

<p>For that, Rust offers you the <code>extern crate</code> declaration:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">num</span>;<span class="comment">
// `num` ships with Rust (much like `extra`; more details further down).

</span><span class="kw">fn</span> <span class="ident">main</span>() {<span class="comment">
    // The rational number '1/2':
    </span><span class="kw">let</span> <span class="ident">one_half</span> <span class="op">=</span> ::<span class="ident">num</span>::<span class="ident">rational</span>::<span class="ident">Ratio</span>::<span class="ident">new</span>(<span class="number">1</span>, <span class="number">2</span>);
}
</pre>

<p>A statement of the form <code>extern crate foo;</code> will cause <code>rustc</code> to search for the crate <code>foo</code>,
and if it finds a matching binary it lets you use it from inside your crate.</p>

<p>The effect it has on your module hierarchy mirrors aspects of both <code>mod</code> and <code>use</code>:</p>

<ul>
<li><p>Like <code>mod</code>, it causes <code>rustc</code> to actually emit code:
The linkage information the binary needs to use the library <code>foo</code>.</p></li>
<li><p>But like <code>use</code>, all <code>extern crate</code> statements that refer to the same library are interchangeable,
as each one really just presents an alias to an external module (the crate root of the library
you're linking against).</p></li>
</ul>

<p>Remember how <code>use</code>-statements have to go before local declarations because the latter shadows the former?
Well, <code>extern crate</code> statements also have their own rules in that regard:
Both <code>use</code> and local declarations can shadow them, so the rule is that <code>extern crate</code> has to go in front
of both <code>use</code> and local declarations.</p>

<p>Which can result in something like this:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">num</span>;

<span class="kw">use</span> <span class="ident">farm</span>::<span class="ident">dog</span>;
<span class="kw">use</span> <span class="ident">num</span>::<span class="ident">rational</span>::<span class="ident">Ratio</span>;

<span class="kw">mod</span> <span class="ident">farm</span> {
    <span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">dog</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"woof"</span>); }
}

<span class="kw">fn</span> <span class="ident">main</span>() {
    <span class="ident">farm</span>::<span class="ident">dog</span>();
    <span class="kw">let</span> <span class="ident">a_third</span> <span class="op">=</span> <span class="ident">Ratio</span>::<span class="ident">new</span>(<span class="number">1</span>, <span class="number">3</span>);
}
</pre>

<p>It's a bit weird, but it's the result of shadowing rules that have been set that way because
they model most closely what people expect to shadow.</p>

<h2 id="crate-metadata-and-settings" class="section-header"><a href="#crate-metadata-and-settings">18.8 Crate metadata and settings(crate元数据和设置)</a></h2>
<p>For every crate you can define a number of metadata items, such as link name, version or author.
You can also toggle settings that have crate-global consequences. Both mechanism
work by providing attributes in the crate root.</p>

<p>For example, Rust uniquely identifies crates by their link metadata, which includes
the link name and the version. It also hashes the filename and the symbols in a binary
based on the link metadata, allowing you to use two different versions of the same library in a crate
without conflict.</p>

<p>Therefore, if you plan to compile your crate as a library, you should annotate it with that information:</p>
<pre class="rust "><span class="comment">// `lib.rs`

</span><span class="attribute">#<span class="op">!</span>[<span class="ident">crate_id</span> <span class="op">=</span> <span class="string">"farm#2.5"</span>]</span><span class="comment">

// ...
</span></pre>

<p>You can also specify crate id information in a <code>extern crate</code> statement.  For
example, these <code>extern crate</code> statements would both accept and select the
crate define above:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">farm</span>;
<span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">farm</span> <span class="op">=</span> <span class="string">"farm#2.5"</span>;
<span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">my_farm</span> <span class="op">=</span> <span class="string">"farm"</span>;
</pre>

<p>Other crate settings and metadata include things like enabling/disabling certain errors or warnings,
or setting the crate type (library or executable) explicitly:</p>
<pre class="rust "><span class="comment">// `lib.rs`
// ...

// This crate is a library ("bin" is the default)
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">crate_id</span> <span class="op">=</span> <span class="string">"farm#2.5"</span>]</span>
<span class="attribute">#<span class="op">!</span>[<span class="ident">crate_type</span> <span class="op">=</span> <span class="string">"lib"</span>]</span><span class="comment">

// Turn on a warning
</span><span class="attribute">#[<span class="ident">warn</span>(<span class="ident">non_camel_case_types</span>)]</span>
</pre>

<h2 id="a-minimal-example" class="section-header"><a href="#a-minimal-example">18.9 A minimal example(小例子)</a></h2>
<p>Now for something that you can actually compile yourself.</p>

<p>We define two crates, and use one of them as a library in the other.</p>
<pre class="rust "><span class="comment">// `world.rs`
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">crate_id</span> <span class="op">=</span> <span class="string">"world#0.42"</span>]</span>

<span class="kw">pub</span> <span class="kw">fn</span> <span class="ident">explore</span>() <span class="op">-&gt;</span> <span class="kw-2">&amp;</span><span class="lifetime">'static</span> <span class="ident">str</span> { <span class="string">"world"</span> }
</pre>
<pre class="rust "><span class="comment">// `main.rs`
</span><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">world</span>;
<span class="kw">fn</span> <span class="ident">main</span>() { <span class="macro">println</span><span class="macro">!</span>(<span class="string">"hello {}"</span>, <span class="ident">world</span>::<span class="ident">explore</span>()); }
</pre>

<p>Now compile and run like this (adjust to your platform if necessary):</p>

<pre><code class="language-{.notrust}">&gt; rustc --crate-type=lib world.rs  # compiles libworld-&lt;HASH&gt;-0.42.so
&gt; rustc main.rs -L .               # compiles main
&gt; ./main
"hello world"</code></pre>

<p>Notice that the library produced contains the version in the file name
as well as an inscrutable string of alphanumerics. As explained in the previous paragraph,
these are both part of Rust's library versioning scheme. The alphanumerics are
a hash representing the crate's id.</p>

<h2 id="the-standard-library-and-the-prelude" class="section-header"><a href="#the-standard-library-and-the-prelude">18.10 The standard library and the prelude(标准库和预装模块)</a></h2>
<p>While reading the examples in this tutorial, you might have asked yourself where all
those magical predefined items like <code>range</code> are coming from.</p>

<p>The truth is, there's nothing magical about them: They are all defined normally
in the <code>std</code> library, which is a crate that ships with Rust.</p>

<p>The only magical thing that happens is that <code>rustc</code> automatically inserts this line into your crate root:</p>
<pre class="rust "><span class="kw">extern</span> <span class="kw">crate</span> <span class="ident">std</span>;
</pre>

<p>As well as this line into every module body:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">std</span>::<span class="ident">prelude</span>::<span class="op">*</span>;
</pre>

<p>The role of the <code>prelude</code> module is to re-export common definitions from <code>std</code>.</p>

<p>This allows you to use common types and functions like <code>Option&lt;T&gt;</code> or <code>range</code>
without needing to import them. And if you need something from <code>std</code> that's not in the prelude,
you just have to import it with an <code>use</code> statement.</p>

<p>For example, it re-exports <code>range</code> which is defined in <code>std::iter::range</code>:</p>
<pre class="rust "><span class="kw">use</span> <span class="ident">iter_range</span> <span class="op">=</span> <span class="ident">std</span>::<span class="ident">iter</span>::<span class="ident">range</span>;

<span class="kw">fn</span> <span class="ident">main</span>() {<span class="comment">
    // `range` is imported by default
    </span><span class="kw">for</span> _ <span class="kw">in</span> <span class="ident">range</span>(<span class="number">0</span>, <span class="number">10</span>) {}<span class="comment">

    // Doesn't hinder you from importing it under a different name yourself
    </span><span class="kw">for</span> _ <span class="kw">in</span> <span class="ident">iter_range</span>(<span class="number">0</span>, <span class="number">10</span>) {}<span class="comment">

    // Or from not using the automatic import.
    </span><span class="kw">for</span> _ <span class="kw">in</span> ::<span class="ident">std</span>::<span class="ident">iter</span>::<span class="ident">range</span>(<span class="number">0</span>, <span class="number">10</span>) {}
}
</pre>

<p>Both auto-insertions can be disabled with an attribute if necessary:</p>
<pre class="rust "><span class="comment">// In the crate root:
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">no_std</span>]</span>
</pre>
<pre class="rust "><span class="comment">// In any module:
</span><span class="attribute">#<span class="op">!</span>[<span class="ident">no_implicit_prelude</span>]</span>
</pre>

<p>See the <a href="http://static.rust-lang.org/doc/master/std/index.html">API documentation</a> for details.</p>

<h1 id="what-next?" class="section-header"><a href="#what-next?">19 What next?(下一步)</a></h1>
<p>Now that you know the essentials, check out any of the additional
guides on individual topics.</p>

<ul>
<li><a href="http://static.rust-lang.org/doc/master/guide-pointers.html">Pointers</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-lifetimes.html">Lifetimes</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-tasks.html">Tasks and communication</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-macros.html">Macros</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-ffi.html">The foreign function interface</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-container.html">Containers and iterators</a></li>
<li><a href="http://static.rust-lang.org/doc/master/rustdoc.html">Documenting Rust code</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-testing.html">Testing Rust code</a></li>
<li><a href="http://static.rust-lang.org/doc/master/guide-runtime.html">The Rust Runtime</a></li>
</ul>

<p>There is further documentation on the <a href="https://github.com/mozilla/rust/wiki/Docs">wiki</a>, however those tend to be even more out of date as this document.</p>

    <footer><p>
Copyright © 2011-2014 The Rust Project Developers. Licensed under the
<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>
or the <a href="http://opensource.org/licenses/MIT">MIT license</a>, at your option.
</p><p>
This file may not be copied, modified, or distributed except according to those terms.
</p></footer>



<div style="left: 0px; top: 0px; position: absolute; width: 29px; height: 27px; border: medium none; margin: 0px; padding: 0px; z-index: 2147483647; display: none;" class="sbi_search" id="sbi_camera_button"></div></body></html>
